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

Nyx*_*nyx 26 javascript jquery backbone.js underscore.js

我有一个backbone.js/underscore.js模板,我正在提供一个骨干视图进行渲染.View传递的模型包含一个posts对象数组(我post在模板中调用).

问题:当我尝试遍历数组的所有元素时posts,我收到错误Uncaught SyntaxError: Unexpected token )并在主干View的代码中引用一行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>
Run Code Online (Sandbox Code Playgroud)

小智 51

要回显变量使用<%= %>,但要解析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>
Run Code Online (Sandbox Code Playgroud)