简体   繁体   English

Symfony2:在(导入的)JavaScript中使用树枝变量

[英]Symfony2: using twig variables inside (imported) javascript

Let's say the variable is called 'myvar'. 假设该变量称为“ myvar”。 I can access its value in twig using {{ myvar }} . 我可以使用{{ myvar }}{{ myvar }}访问其值。

I can also use it inside javascript code, if inside the same twig page, by doing 我也可以在javascript代码中使用它(如果在同一树枝页面中),方法是:

<script>
//some javascript code
myJSVar = {{ myvar }};
//other javascript code
</script>

The question is: if I import a js (eg I have a main.js where I put all the common js stuff) is there a way do the same? 问题是:如果我导入一个js(例如,我有一个main.js,我在其中放置了所有常见的js内容),有没有办法做到这一点?

I've read about a solution for CSS ( Symfony2: Use Twig variable in stylesheet ) which is a bit convoluted, and another point of reference might be here ( Using Twig as an Assetic filter for JavaScript in Symfony2 ). 我已经读到了一个CSS的解决方案( Symfony2:在样式表中使用Twig变量 ),这有点令人费解,而另一个参考点可能在这里( 使用Twig作为Symfony2中JavaScript的Assetic过滤器 )。 Any other options? 还有其他选择吗?

In practice what I need is passing a global variable, something that you'd find in config.yml. 实际上,我需要传递一个全局变量,您可以在config.yml中找到该变量。 It's a path basically, which is different in production and in development. 基本上,这是一条路径,在生产和开发上都不同。

Thank you! 谢谢!

Perhaps you could do something like: 也许您可以执行以下操作:

<div id="somediv" data-var="{{ myvar }}"></div>. 

And then on you main.js: 然后在您main.js上:

var myJSVar = $('#somediv').data('var');

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

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