Sergio Negri Sergio Negri - 6 days ago 5
Twig Question

Symfony2: using twig variables inside (imported) javascript

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 (e.g. 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!

Answer

Perhaps you could do something like:

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

And then on you main.js:

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