Javascript 将变量从树枝传递给 js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27381591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass variable from twig to js
提问by nowiko
Is there some way to pass variables from twig to javascript file that lay in public/js directory of bundle. Or do I need to assign my variables in template and then include my script file where vars will be used?
有什么方法可以将变量从树枝传递到位于 bundle.js 的 public/js 目录中的 javascript 文件。或者我是否需要在模板中分配我的变量,然后将我的脚本文件包含在将使用变量的位置?
回答by fire
Assign the variable in the template and pick it up with javascript...
分配模板中的变量并使用 javascript 获取它...
<script>
var foo = '{{ foo }}';
alert(foo);
</script>
回答by qooplmao
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. This would mean that your javascript wouldn't necessarily be coupled to your twig file.
无需将您的 javascript 文件作为模板的另一种方法是将 javascript 值作为data-*属性,然后从您的 javascript 文件中获取它。这意味着您的 javascript 不一定会耦合到您的树枝文件。
<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;
回答by numediaweb
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);

