5

Can we write javascript code in twig template?

Its needed to write javascript code in twig template.

When we are writting the same code in custom.js file that particular code is not working in it.

How to write javascript code directly into the twig template?

  • The code in your js file maybe doesn't work because the HTML is not rendered yet. Try to write your code in a document.ready function or use $('body').on('click', selector,function()) instead of $(selector).click(function()); Also check if you get any errors in your console. – Ismini Oct 11 '17 at 10:09
5

Yes, you can write JS code in a twig template. I can't think of any syntax crossovers so you should be able to literally write it as-is.

Indeed this works fine in html.twig.html:

<script>
  (function(val) {
    console.log(val);
  })('test');
</script>

If you're having syntax trouble, you can always escape it with raw, but it should be unnecessary:

{% raw %}
<script>
  (function(val) {
    console.log(val);
  })('test');
</script>
{% endraw %}
  • thanks clive and whats about the php code can we use directly into twig template as javascript. – user59414 Oct 11 '17 at 10:40
  • 1
    You need to preprocess it to get php vars into twig, you can't add php code to a template. Well you can, but it won't be executed – Clive Oct 11 '17 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy