如何调用 jquery-templates 中嵌套的 {{tmpl}} 标签中的函数?
这是一个基于 jquery-tmpl API 文档中的代码的简单示例。我想使用嵌套的 {{tmpl}} 标签 - 这里是“titleTemplate”。我想在外部模板和嵌套模板中使用各种辅助函数。此示例有一个名为“embolden”的简单辅助函数,该函数被传递给初始 tmpl() 调用。
以下作品。我能够在 titleTemplate 中放大名称数据。但看起来很乱。有没有更干净的方法来做到这一点?由于 formatHelpers 被传递到原始 tmpl() 调用中,是否真的有必要将其也传递到 {{tmpl}} 标记中?
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl($item.data, formatHelpers) "#titleTemplate"}}
<tr class="detail"><td>Director: ${$item.embolden(Director)}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${$item.embolden($item.data.Name)}</td></tr>
</script>
<table><tbody id="movieList"></tbody></table>
<script>
var formatHelpers = {
embolden: function(i) {
return "*" + i + "*";
}
};
var movies = [
{ Name: "The Red Violin", Director: "François Girard" },
{ Name: "Eyes Wide Shut", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", Director: "Mauro Bolognini" }
];
/* Render the template with the movies data */
$( "#movieTemplate").tmpl(movies, formatHelpers).appendTo("#movieList");
</script>
This is a simple example based on the code in the jquery-tmpl API docs. I'd like to use a nested {{tmpl}} tag--here the "titleTemplate". I'd like to use various helper functions in both the outer template and the nested template. This example has one trivial helper function called "embolden" that's passed to the initial tmpl() call.
The following works. I'm able to embolden the Name data inside the titleTemplate. But it seems messy. Is there a cleaner way to do this? Since formatHelpers is passed into the original tmpl() call, is it really necessary to pass it into the {{tmpl}} tag as well?
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl($item.data, formatHelpers) "#titleTemplate"}}
<tr class="detail"><td>Director: ${$item.embolden(Director)}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${$item.embolden($item.data.Name)}</td></tr>
</script>
<table><tbody id="movieList"></tbody></table>
<script>
var formatHelpers = {
embolden: function(i) {
return "*" + i + "*";
}
};
var movies = [
{ Name: "The Red Violin", Director: "François Girard" },
{ Name: "Eyes Wide Shut", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", Director: "Mauro Bolognini" }
];
/* Render the template with the movies data */
$( "#movieTemplate").tmpl(movies, formatHelpers).appendTo("#movieList");
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的示例,您所需要做的就是
jsfiddle上的代码示例。
您可以执行此操作的另一种方法是在全局范围内定义 formatHelpers,您应该能够直接在模板中调用它们。
在模板内部,您可以执行以下操作:
jsfiddle 上的代码示例。
With your example, all you need to do is
Code example on jsfiddle.
Another way you can do this is to define your formatHelpers in global scope you should be able to call them directly in your template.
And inside of your template you can do the following:
Code example on jsfiddle.