0

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!

Sergio Negri
  • 2,023
  • 2
  • 16
  • 38
  • Did you check this already? http://stackoverflow.com/questions/12572506/symfony2-twig-and-javascript . Besides, the "fastest" alternative solution you have (**despite not the cleverest**) is to extend your template and write an inline script. (Also, another possible exploit is to **embed** the file by passing the variables you need, despite it may create you many issues later) – briosheje Jun 24 '15 at 07:38
  • I did not get that one, but meanwhile I indeed solved it as they suggest in the link you sent (second solution, which is perfect for my case). Thank you for your time! – Sergio Negri Jun 24 '15 at 07:43

1 Answers1

0

Perhaps you could do something like:

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

And then on you main.js:

var myJSVar = $('#somediv').data('var');
Ubuntu Man
  • 50
  • 1
  • 10