在 underscore.js 模板引擎中运行模板中的模板(递归)
我正在使用backbone.js 和underscore.js 构建一个javascript 应用程序。经过几个小时的阅读并尝试在如下所示的模板中运行模板后,它变得越来越令人沮丧。
我的模板使用 underscore.js 模板引擎中的构建:
<script id="navigation_template" type="text/template">
<div><%= title %>
<% _.each(children, function(child) { %>
<% render_this_template_recursively(child) %>
<% }); %>
</div>
</script>
我想为每个子元素渲染此模板( render_this_template_recursively(child) )。
我该怎么做?
谢谢
I am using backbone.js and underscore.js to build an javascript application. Since hours of reading and trying to run a template within a template like below, it is getting more and more frustrating.
My template using the build in underscore.js template engine:
<script id="navigation_template" type="text/template">
<div><%= title %>
<% _.each(children, function(child) { %>
<% render_this_template_recursively(child) %>
<% }); %>
</div>
</script>
I would like to render this template for every child element ( render_this_template_recursively(child) ).
How can I do this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我没有亲自尝试过这个,但 _.template 返回一个函数(我将其命名为 templateFn 来强调这一点),因此您可以将其传递到模板中,如下所示:
请注意,我正在传递整个模型(假设你的模型有一个children属性,它本身就是骨干模型的集合),你的模板将更改为:
祝你好运。我希望这对你有用
I've not personally tried this but _.template returns a function (I've named it templateFn to emphasize that), so you could pass it into the template like this:
Notice that i'm passing in the whole model (assuming that your model has a children property which is itself a collection of backbone models) and your template would be changed to:
Good luck. I hope this works for you
我刚刚成功尝试了这个。我只用纯 UnderscoreJS 测试了它,没有使用 BackboneJS,但从功能上来说这应该不重要。
这是代码:
I just successfully tried this. I tested it with only pure UnderscoreJS, no BackboneJS but functionally it shouldn't matter.
Here is the code:
我尝试使用 timDunham 和 Ates Goral 提供的示例,但它对我不起作用,所以我对其进行了一些升级。在下面找到它。
视图:
和模板:
它对我来说效果很好。正如您所看到的,主要区别是将配置对象传递到 templateFn 中,而不是参数。希望您会发现它很有用。
I've tried to use example presented by timDunham and Ates Goral, but it did not work for me, so I've made a little upgrade for it. Find it below.
view:
and template:
And it works pretty good for me. The main difference, as you can see, is the passing configuration object into templateFn, instead of arguments. Hope you'll find it useful.
递归模板可以如下所示:
首先,预编译模板:
然后在传递数据和模板本身时调用它:
A recursive template can look something like this:
First, pre-compile your template:
Then call it while passing both your data and the template itself:
我最近使用骨干关系实现了这一点。我创建了一个小提琴,如果您想查看可行的解决方案,我认为它可能会有所帮助: http://jsfiddle.net /blaisco/ADKrK/
我已在下面发布了相关内容。
视图:
html/模板:
I implemented this recently using backbone-relational. I created a fiddle that I thought might be helpful if you want to see a working solution: http://jsfiddle.net/blaisco/ADKrK/
I've posted the relevant bits below.
The view:
The html/template: