在 underscore.js 模板引擎中的模板(递归)中运行模板 [英] Run Template in Template (recursion) within underscore.js template engine

查看:17
本文介绍了在 underscore.js 模板引擎中的模板(递归)中运行模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用backbone.js 和underscore.js 来构建一个javascript 应用程序.由于数小时的阅读和尝试在如下模板中运行模板,它变得越来越令人沮丧.

我的模板使用 underscore.js 模板引擎中的构建:

我想为每个子元素渲染这个模板( render_this_template_recursively(child) ).

我该怎么做?

谢谢

解决方案

我没有亲自尝试过这个,但 _.template 返回一个函数(我将它命名为 templateFn 以强调这一点),所以你可以将它传递到模板如下:

var templateFn = _.template($('#navigation_template').html());$(this.el).html(templateFn({model: this.model, templateFn: templateFn}));

请注意,我正在传递整个模型(假设您的模型有一个 children 属性,它本身就是一个主干模型的集合)并且您的模板将更改为:

祝你好运.我希望这对你有用

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

解决方案

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:

var templateFn = _.template($('#navigation_template').html());

$(this.el).html(templateFn({model: this.model, templateFn: templateFn}));

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:

<script id="navigation_template" type="text/template">
  <div><%= model.escape('title') %>
      <% _.each(model.children, function(child) { %>
          <%= templateFn(child, templateFn) %>
      <% }); %>
  </div>
</script>

Good luck. I hope this works for you

这篇关于在 underscore.js 模板引擎中的模板(递归)中运行模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆