我有一个大致如下所示的下划线模板:
<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
。 .
如果您的模板有可用的 listHeaderTemplate
和 listFooterTemplate
,您可以简单地说:
<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
});
关于javascript - 下划线模板 : passing variables from a parent template to a child template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368595/