Twig variable in extern js file

2019-01-20 03:30发布

问题:

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

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

Thanks,

回答1:

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 %}