如何使用Handlebars和Backbone访问每个变量

时间:2015-11-04 15:44:11

标签: backbone.js handlebars.js

我试图访问每个author内的project.entities变量...任何人都知道为什么我不能{{author}}和我{I}应该做到这一点吗?

查看

        self.$el.html(self.template({
            project: this.model.attributes,
            author: this.model.get('authors')
        }));

模板

     <p class="author">by: {{author.full_name}}</p>
     <!-- author is available here -->
     {{#each project.entities}}
        <div class="audio">
            <div class="title-wave">
                <p class="title">{{this.title}}</p>
                <p class="author">by: {{author.full_name}}</p>
                <!-- author is not available inside of project each loop-->
            </div>
        </div>

1 个答案:

答案 0 :(得分:0)

您没有访问正确的上下文

要访问author,您必须使用project../每个循环中退出一个conext级别。

此行为与Mustache行为不同,如果当前上下文中没有键,则将以递归方式检查父上下文。

不幸的是,Handlebars documentation意味着,但没有说明这种区别。

var template = Handlebars.compile($("#template").html());
$("#rendered").html(template(
    {
        "project": {
            "entities": [
                {
                	"title": "Entity Title"
                }
            ]
        },
        "author": {
            "id"       : 1,
            "full_name": "John Smith",
            "dob"      : "12/12/2012"
        }
    }
));
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="template" type="text/x-handlebars-template">
    <p class="author">by: {{author.full_name}}</p>
     <!-- author is available here -->
     {{#each project.entities}}
        <div class="audio">
            <div class="title-wave">
                <p class="title">{{this.title}}</p>
                <p class="author">by: {{../author.full_name}}</p>
                <!-- To access `author` you have to back out one conext level from the `project` each loop. -->
            </div>
        </div>
    {{/each}}
</script>
<div id="rendered"></div>

相关问题