admin管理员组

文章数量:1352884

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 plete separated js file an ajax call to a known path "_check_coupon".

Any idea to approach this?

Thanks in advance

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 plete separated js file an ajax call to a known path "_check_coupon".

Any idea to approach this?

Thanks in advance

Share Improve this question asked Sep 16, 2012 at 15:52 ElPiterElPiter 4,32410 gold badges57 silver badges82 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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.

I know the answer is old but I came across the same problem and found the following solution by using the verbatim tag.

// {% verbatim %}
(function() {
// {% endverbatim %}
    var val = "{{ myImportVar|raw }}";
// {% verbatim %}

    /**
     * JS Code
     */
     console.log(val);
}());
// {% endverbatim %}

Ive wrapped them in JS ments to make my editor hints etc. working.

本文标签: javascripttwig code in js fileStack Overflow