Let's say the variable is called 'myvar'. I can access its value in twig using {{ myvar }}
.
I can also use it inside javascript code, if inside the same twig page, by doing
<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?
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 ). Any other options?
In practice what I need is passing a global variable, something that you'd find in 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:
var myJSVar = $('#somediv').data('var');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.