简体   繁体   English

将变量从树枝传递给 js

[英]Pass variable from twig to js

Is there some way to pass variables from twig to javascript file that lay in public/js directory of bundle.有没有办法将变量从 twig 传递到位于 bundle 的 public/js 目录中的 javascript 文件。 Or do I need to assign my variables in template and then include my script file where vars will be used?或者我是否需要在模板中分配我的变量,然后将我的脚本文件包含在将使用 vars 的位置?

Assign the variable in the template and pick it up with javascript... 在模板中分配变量并使用javascript将其选中...

<script>
var foo = '{{ foo }}';
alert(foo);
</script>

Another way without having to have your javascript file as a template would be to have the javascript value as a data-* attribute and then get that from your javascript file. 另一种不必将javascript文件作为模板的方法是将javascript值作为data-*属性,然后从javascript文件中获取。 This would mean that your javascript wouldn't necessarily be coupled to your twig file. 这意味着您的javascript不一定会耦合到您的twig文件。

<a href="#" data-id="{{ entity.id }}" id="some-link">Link</a>

With jQuery.. 用jQuery ..

var id = $('#some-link').data('id');

With regular javascript (i think).. 使用常规javascript(我认为)..

var id = document.querySelector('#some-link').dataset.id;

You can use this in your twig 你可以在树枝上使用它

<script type="text/javascript">
    /* <![CDATA[ */
    var settings = {
        example: {{ 'something' | trans }}
        }
    };
    /* ]]> */
</script>

then you can access them in your js: 然后你可以在你的js中访问它们:

console.log(settings.example);

watch this看这个

variable in twig:    fpoint = [{'id': 1},{'id': 2}]

if it is an array如果它是一个数组

var fg = $.parseJSON('{{ fpoint | json_encode | raw }}');
for(k in fg){
  console.log("fpoint: ", fg[k].id);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM