3

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.

3
  • 6
    Don’t do this. Use drupalSettings, construct values in a module or preprocess and attach them.
    – Kevin
    Commented May 21, 2018 at 9:57
  • Is there a reason that you say don't do this? @Kevin Commented May 21, 2018 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. Commented May 21, 2018 at 11:30

1 Answer 1

7

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.

1
  • 1
    This is not going to work because of the cache.
    – gagarine
    Commented Jun 13, 2020 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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