开发者

Read jquery variable inside a twig block

Mainly, I need to read a jQuery variable inside a twig block, but I don't know how. I've tried different approaches without no success

Take this piece of code as an example about what I'm trying to do.

$('table tbody tr').each开发者_运维技巧(function(index) {
     {% set i = index %} <-- does NOT work
     $('#test_form_' + index + '_name').style.color = "blue"   <-- That works  
     $('#test_form_' + index + '_name option[value =' +
         {{ names[i].id is defined ? names[i].id : '' }}
         + ']').attr("selected","selected"); <-- Need of JQuery index variable?¿?
})

Any help?

Thanks


Simply put, as mentioned by csg in a comment to Kelly Cooks answer; it is not possible.

The Twig templates are compiled to regular PHP code, which executes on the server, while the JavaScript is interpreted and executed on runtime.

I'm not entirely sure what you want to do with the table in your example? But I've found Twigs built-in loop variables (loop.index, loop.first, loop.last and so on) really helpful.

I think the tricky part (for me) has been to find a good strategy of integrating JavaScript into the pages. I've taken the following approach; do as much as possible in Twig (output, adding CSS-classes to elements, and so on), then consider the page more or less "static HTML" and start with the JavaScript to achieve the desired functionality (which includes, if I'm forced to, going back to Twig and adding some extra attributes like IDs or other stuff).

If you want Twig to directly integrate with the JS, you might be able to do it by having the largest part of the JS script in an external file, but also declare some of it inline (where you could use Twig to construct the JS code itself :-) )

Good luck! ManneW

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜