Javascript 在主干/下划线'中使用循环;s模板
我有一个backbone.js/underline.js模板,我正在将其输入到主干视图中进行渲染。视图被传递给一个模型,该模型包含对象的数组Javascript 在主干/下划线'中使用循环;s模板,javascript,jquery,backbone.js,underscore.js,Javascript,Jquery,Backbone.js,Underscore.js,我有一个backbone.js/underline.js模板,我正在将其输入到主干视图中进行渲染。视图被传递给一个模型,该模型包含对象的数组posts(我在模板中称之为post) 问题:当我尝试循环遍历数组的所有元素帖子,我得到一个错误未捕获的语法错误:意外标记),并引用主干视图的代码模板:u.template($('.\tpl_SetView').html()) 我是否不正确地执行循环导致了此错误 模板代码 <script type="text/template" id="tpl_Set
posts
(我在模板中称之为post
)
问题:当我尝试循环遍历数组的所有元素帖子
,我得到一个错误未捕获的语法错误:意外标记)
,并引用主干视图的代码模板:u.template($('.\tpl_SetView').html())
我是否不正确地执行循环导致了此错误
模板代码
<script type="text/template" id="tpl_SetView">
<div class="row_4">
<div class="photo_container">
<div class="set_cover">
<img src="/<%= posts[0].thumb_subpath %><%= posts[0].img_filename %>" width=240 />
</div>
<div class="set_thumbs">
<%= _.each(posts, function(post) { %>
<img src="<%= post.thumb_subpath %><%= posts.img_filename %>" width=55 />
<%= }); %>
</div>
</div>
</div>
</script>
“宽度=240/>
“宽度=55/>
我想你会发现问题出在以下几行:
“宽度=55/>
根据我对下划线计算模板的记忆,这些行没有多大意义。每个项都是单独计算的。也就是说,它们必须是完全可计算的表达式,而不是部分函数块
编辑:事实上,James是对的。可以单独定义(最终归结为一个大javascript字符串)。它是转义的,插值表达式必须是单独的表达式
编辑II:即使如此,在评估上下文中,我认为函数块的使用仍然可能会创建一个奇异的javascript字符串,该字符串的评估可能与预期不符……我必须考虑一下。它可能仍然可以完全正常工作。要回显变量,请使用
,但要解析javascript代码,只需使用
例如:
// In your Backbone View
var posts = {"posts": this.model.toJSON()};
var template = _.template($("#tpl_SetView").html(), posts);
// In your template
<div class="row_4">
<div class="photo_container">
<div class="set_cover">
<img src="/<%= _.escape(posts[0].thumb_subpath) %><%= _.escape(posts[0].img_filename) %>" width=240 />
</div>
<div class="set_thumbs">
<% _.each(posts, function(post){ %>
<img src="<%= _.escape(post.thumb_subpath) %><%= _.escape(posts.img_filename) %>" width=55 />
<% }); %>
</div>
</div>
</div>
//在主干视图中
var posts={“posts”:this.model.toJSON()};
var template=35;.template($(“35; tpl_SetView”).html(),posts);
//在模板中
“宽度=240/>
“宽度=55/>
我认为最好将代码组织到新的模型和视图中。在不好的实践中循环使用模板我很好奇为什么你认为循环使用模板是不好的实践。我刚刚实现了James Woodruff下面给出的答案,用于构建一个选择选项列表(根据情况而有所不同)在我看来,循环遍历选项数组要容易得多,而不是创建一个名为“selectOption”的单独视图,然后迭代地将其附加到。我缺少什么吗?