2

I have a twig file of a custom module. It has a <script></script> section and I need to print a twig variable inside that section. How do I do this?

{{ set twigVariable = '123456' }}

<script>
    function myFunc() {
        var myJsVar = {{ twigVariable }};
    }
</script>

The variable does not print when I write like above.

  • 5
    Don’t do this. Use drupalSettings, construct values in a module or preprocess and attach them. – Kevin May 21 '18 at 9:57
  • Is there a reason that you say don't do this? @Kevin – i am batman May 21 '18 at 11:25
  • 4
    Because it is bad practice to mix up theming and functional parts as JavaScript in a template. You should keep your templates clean and use template pre-processing to attach any scripts or script settings required by your frontend features. – Mario Steinitz May 21 '18 at 11:30
3

I'll spare to tell that it's a bad practice to add custom script blocks to templates, and just point out the error(s):

(1) To set the variable content, you have to wrap set into a {% %} block, not {{ }}.

(2) You most probably want the value as JavaScript string, so don't forget to wrap it in " ".

This sums up to

{% set twigVariable = '123456' %}

<script>
  function myFunc() {
    var myJsVar = "{{ twigVariable }}";
  }
</script>

Which should be working just fine.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.