外部JS文件中的Twig变量 [英] Twig variable in external JS file

查看:91
本文介绍了外部JS文件中的Twig变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想外部化我的JS代码,但是代码中有Twig变量.
要使它起作用,您有什么窍门?

I would like to externalize my JS code, but there is Twig variable in the code.
What are your tricks to make this working?

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

推荐答案

当您需要将细枝变量传递给外部javascript文件时,有两种方法

There a two approaches when you need to pass a twig variable to an external javascript file

  1. 在树枝模板中的脚本块内定义变量

<!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>

对于这种方法,我通常添加一个名为"javascript"的代码块.封锁我的主/基本模板

For this approach I usally add a block called "javascript" block in my main/base 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 %}


  1. 借助data-*属性将变量传递给javascript
  1. Pass the variables to javascript with the aid of data-* attributes

<div data-foo="{{ foo }}">...</div>

$(function() {
    $(document).on('click', '.button', function(e) {
        console.log($('div[data-foo]').data('foo'));
    });
});


旁注:如果要将对象或数组传递给twig,则始终可以使用json_encode过滤器,该过滤器会将变量转换为有效的javascript对象


Sidenote: if you want to pass an object or an array to twig you can always use the json_encode filter, which will convert the variable to a valid javascript object

如果要控制json_encode筛选器公开哪些对象属性,可以始终实现接口

If you want to have control over which object properties are exposed by the json_encode filter you can always implement the interface Serializable

这篇关于外部JS文件中的Twig变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆