读取树枝块内的jquery变量
主要是,我需要读取 twig 块内的 jQuery 变量,但我不知道如何读取。 我尝试了不同的方法,但没有成功
以这段代码为例,说明我正在尝试做什么。
$('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?¿?
})
有什么帮助吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,正如 csg 在对 Kelly Cooks 回答的评论中提到的那样;这是不可能的。
Twig 模板被编译为常规 PHP 代码,在服务器上执行,而 JavaScript 在运行时解释和执行。
我不完全确定您想对示例中的表格做什么?
但我发现 Twigs 内置循环变量(loop.index、loop.first、loop.last 等)非常有用。
我认为(对我来说)棘手的部分是找到将 JavaScript 集成到页面中的好策略。我采取了以下方法;在 Twig 中尽可能多地进行操作(输出、向元素添加 CSS 类等),然后将页面视为或多或少的“静态 HTML”,并从 JavaScript 开始实现所需的功能(其中包括,如果我'我被迫,回到 Twig 并添加一些额外的属性,如 ID 或其他东西)。
如果您希望 Twig 直接与 JS 集成,您可以通过将 JS 脚本的最大部分放在外部文件中来实现,但也可以将其中的一些声明为内联(您可以使用 Twig 来构造 JS 代码)本身 :-) )
祝你好运!
曼恩
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