在主干/下划线中使用循环's模板

Using loops in backbone/underscore's templates

本文关键字:循环 模板 下划线      更新时间:2023-09-26

我有一个backbone.js/donscore.js模板,我正在将其输入到主干视图中进行渲染。View传递了一个模型,该模型包含对象的数组posts(我在模板中称之为post)。

问题:当我试图循环遍历数组posts的所有元素时,我会得到一个错误Uncaught SyntaxError: Unexpected token ),并引用主干视图代码template: _.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>

要回显变量,请使用<%= %>,但要解析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>

我想你会发现问题出在以下几行:

<%= _.each(posts, function(post) { %>
    <img src="<%= post.thumb_subpath %><%= posts.img_filename %>" width=55 />
<%= }); %>

根据我对下划线评估模板的记忆,这些行没有多大意义每个<%=..%>项目单独评估。。也就是说,它们必须是完整的可评估表达式,而不是部分函数块

编辑:实际上,詹姆斯是对的<%.%>可以单独定义(最后都归结为一个大的javascript字符串)。它被转义,插值表达式必须是单独的表达式。

编辑II:即便如此,在评估上下文中,我认为使用函数块仍然可能创建一个奇怪的javascript字符串,该字符串的评估结果可能不完全符合预期。。。我得好好考虑一下。也许还是可以的。