javascript - 下划线模板 : passing variables from a parent template to a child template

标签 javascript backbone.js underscore.js marionette underscore.js-templating

我有一个大致如下所示的下划线模板:

<script type="text/template" id="list-template">
    <%= listHeaderTemplate(); %>
    stuff that
    displays a list
    <%= listFooterTemplate(); %>
</script>

<script type="text/template" id="list-footer-template">
    <%= foo %>
</script>

<script>
listTemplate = _.template($("#list-template").html());
listHeaderTemplate = _.template($("#list-header-template").html());
listFooterTemplate = _.template($("#list-footer-template").html());
</script>

我想做的是将传递给 listTemplate() 的全套变量传递给 listFooterTemplate()。例如,

listTemplate({foo: "foo"});

我可以通过修改 list-template 中对 listHeaderTemplate()/listFooterTemplate() 的调用来将局部变量打包到字典中(即 listFooterTemplate({foo: foo});)来做到这一点,但这似乎相当繁琐,尤其是当正在使用大量变量,这需要我知道列表模板内部可能使用哪些变量列表页脚模板。

最佳答案

当你编译一个 Underscore 模板时,Underscore 会把你的模板翻过来并构建一个看起来或多或少像这样的函数:

function(obj) {
    // Some set up...
    with(obj || {}) {
        // The template as JavaScript...
    }
    return theTemplateText;
}

您不能依赖于被称为 obj 的参数,它迟早会失效。您应该可以安全访问 arguments对象虽然。有了arguments,您就可以使用与当前函数完全相同的参数调用其他函数,而不必知道参数是什么,您只需使用apply。 .

如果您的模板有可用的 listHeaderTemplatelistFooterTemplate,您可以简单地说:

<script type="text/template" id="list-template">
    <%= listHeaderTemplate.apply(this, arguments) %>
    stuff that
    displays a list
    <%= listFooterTemplate.apply(this, arguments) %>
</script>

一种简单的方法是将这些函数作为参数传递给您的模板:

var listTemplate       = _.template($("#list-template").html());
var listHeaderTemplate = _.template($("#list-header-template").html());
var listFooterTemplate = _.template($("#list-footer-template").html());

var html = listTemplate({
    foo: 11,
    listHeaderTemplate: listHeaderTemplate,
    listFooterTemplate: listFooterTemplate
});

演示:http://jsfiddle.net/ambiguous/vwjm1kta/

关于javascript - 下划线模板 : passing variables from a parent template to a child template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368595/

相关文章:

javascript - 为什么我的 Regex 使用 "++"而不是任何其他特殊字符组合创建内部服务器错误?

javascript - 不了解 Backbone 的工作原理

Javascript - Lodash/Underscore 比较两个对象并根据它们的键更改值

javascript - 比较 underscorejs 中的两个对象数组

javascript - meteor 排序不区分大小写

javascript - 如何将漂移 JavaScript 添加到 readthedocs 站点?

javascript - 业力 + AngularJS + 剑道 : Kendo-grid testing is not working

javascript - AngularJs ng-model 从 json 绑定(bind)

javascript - 为什么我的 javascript Backbone.js 模型共享其父类的相同 "instance"?

javascript - Backbone & Underscore 未定义,加载思想