Javascript 下划线模板:将变量从父模板传递到子模板
我有一个下划线模板,大致如下所示:Javascript 下划线模板:将变量从父模板传递到子模板,javascript,backbone.js,underscore.js,marionette,underscore.js-templating,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
<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>
function(obj) {
// Some set up...
with(obj || {}) {
// The template as JavaScript...
}
return theTemplateText;
}
我可以通过修改list template中对listHeaderTemplate()/listFooterTemplate()的调用来实现这一点,以将局部变量打包到字典中(即listFooterTemplate({foo:foo});),但这似乎相当繁重,特别是在使用大量变量时,它要求我知道列表模板的内部,列表页脚模板可能使用哪些变量 编译下划线模板时,下划线会将模板从内到外转换,并构建一个大致如下所示的函数:
<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>
function(obj) {
// Some set up...
with(obj || {}) {
// The template as JavaScript...
}
return theTemplateText;
}
您不能依赖于调用的参数obj
,该参数很快或稍后都会中断。不过,您应该可以安全访问该对象。拥有参数
允许您使用与当前函数完全相同的参数调用其他函数,而无需知道参数是什么,您只需使用
如果您的模板有可用的listHeaderTemplate
和listFooterTemplate
,您可以简单地说:
<script type="text/template" id="list-template">
<%= listHeaderTemplate.apply(this, arguments) %>
stuff that
displays a list
<%= listFooterTemplate.apply(this, arguments) %>
</script>
演示:或者,可以通过JSON.stringify和HTML data-*属性传递数据对象
<script type="text/template" id="list-template">
<div id="my-list-template" data-us-tmpl-data="<%= JSON.stringify(data) %>">
</div>
</script>