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 badges2 Answers
Reset to default 8You 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
版权声明:本文标题:javascript - twig code in js file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743905777a2559495.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论