Twig variable in extern js file

ぃ、小莉子 提交于 2019-12-17 07:50:57

问题


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


来源:https://stackoverflow.com/questions/37604063/twig-variable-in-extern-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!