XZKS XZKS - 5 months ago 26
Javascript Question

Twig variable in extern js file

I want to external my js code but there is twig variable. What are your tricks ?

team: {{ 'Select your team'|trans }}


Thanks,

Answer

I just set my twig vars as globals before requiring any javascript files.

<!DOCTYPE html>
<html>
   <head>
      <title></title>
   </head>
   <body>
       <script>
           var my_twig_var = {% if twig_var is defined %}'{{ twig_var }}'{% else %}null{% endif %}
       </script>
       <script src="scripts/functions.js"></script>
   </body>
</html>

Another aproach I use is to forsee a javascript block in my main template

base.twig.html

<!DOCTYPE html>
<html>
   <head>
      <title></title>
   </head>
   <body>
       {% block body %}
       {% endblock %}
       {% block javascript %}
       {% endblock %}
   </body>
</html>

page.html.twig

{% extends base.twig.html %}
{% block body%}
<h1>Hello World</h1>
{% endblock %}
{% block javascript %}
<script>
  alert('{{ twig_var|default('Hello World') }}');
</script>
{% endblock %}
Comments