Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig code in js file

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

like image 453
ElPiter Avatar asked Jun 27 '26 23:06

ElPiter


1 Answers

You can either embed such path in a data-path attribute in a DOM element, like:

<div id="widget" data-path="{{ path('_check_coupon') }}"> ... </div>

Then just fetch it:

$.post( $('#widget').data('path') ,{code: coupon_code}, function(json) {
    // do whatever...
});

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 action attribute.


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.

like image 146
moonwave99 Avatar answered Jun 30 '26 12:06

moonwave99