Using symfony2 with twig templates, I normally use js embedded inside the *html.twig file to dinamize yet more the pages.
What if I have external JS files attached to my page? How could I introduce twig code inside them?
I know it sounds sort of wears, but it is not that much when trying to redirect from javascript to a known symfony path. Just like this:
$.post("{{ path('_check_coupon') }}",{code: coupon_code}, function(json) {
// do whatever...
});
As you can see, I have in a complete separated js file an ajax call to a known path "_check_coupon".
Any idea to approach this?
Thanks in advance
You can either embed such path in a
data-pathattribute in a DOM element, like:Then just fetch it:
That’s a vanilla approach, yet more maintainable that having both js and twig mixed in a single file – at least you won’t get syntax highlight.
Of course if you are dealing with forms, just fetch form’s
actionattribute.Anyway I advise you not to have both JS and markup on the same page: you won’t be able to cache scripts, nor to minify them, so consider decoupling them unless it’s just very very few lines involved. Feel free to check my little library about.