Twig variable in extern js file

2019-01-20 03:52发布

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

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

Thanks,

1条回答
beautiful°
2楼-- · 2019-01-20 04:29

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 %}
查看更多
登录 后发表回答