关于ember.js:递归模板Ember / Handlebars

Recursive template Ember/Handlebars

由于某种原因,我无法在模板中调用助手。引发错误,指出我的助手未定义。

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/x-handlebars" id="catalog">
   
        <ul class="list-group">
            {{#each catalog.catalog_categories}}
               {{categoryHelper this}} // This works !!!
            {{/each}}
       
</ul>

   


<script id="categories-template" data-template-name='test' type="text/x-handlebars-template">
   
        <li class="list-group-item">
           {{ category.category_name_fr_sh }} // French name of category
       
</li>
     

   
    {{#if category.category_children}}    
        {{#each category.category_children}}
            {{categoryHelper this}} // This throw error saying that the helper is undefined
        {{/each}}
    {{/if}}


//app.js
Ember.Handlebars.helper('categoryHelper', function(category) {
    var template = Handlebars.compile($('script#categories-template').html());
    return new Handlebars.SafeString(template({category: category}));
});

编辑:
这是一个jsfiddle
http://jsfiddle.net/CycS8/


在ember引导程序中,它将使用选择器script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]查找所有模板,并且对于每个模板,它将使用适当的编译器引擎进行编译:

Ember.Handlebars.compile用于具有type="text/x-handlebars的脚本,Handlebars.compile对于type="text/x-raw-handlebars的脚本。

编译后,将从dom中删除脚本标签。

助手中的$('script#categories-template').html()可能不返回任何内容。因为模板不在dom中。

我认为以下方法可能有效:

模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script type="text/x-handlebars" id="catalog">
   
        <ul class="list-group">
            {{#each catalog.catalog_categories}}
               {{categoryHelper this}}
            {{/each}}
       
</ul>

   


<script id="categories-template" type="text/x-raw-handlebars">
   
        <li class="list-group-item">
           {{ category.category_name_fr_sh }} // French name of category
       
</li>
   
   
    {{#each category.category_children}}
        {{categoryHelper this}}
    {{/each}}

app.js

1
2
3
4
Ember.Handlebars.helper('categoryHelper', function(category) {
    var template = Ember.TEMPLATES['categories-template'];
    return new Handlebars.SafeString(template({category: category}));
});

更新

Ember提供渲染视图帮助器,我认为您可以使用以下方法来实现此功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script id="catalog" type="text/x-handlebars">
   
        <ul class="list-group">
            {{#each catalog.catalog_categories}}
               {{render"categories-template" this}}
            {{/each}}
       
</ul>

   


<script id="categories-template" type="text/x-handlebars">
   
        <li class="list-group-item">
           {{ category.category_name_fr_sh }} // French name of category
       
</li>
         
   
    {{#each category.category_children}}
        {{render"categories-template" this}}
    {{/each}}


您的类型错误,在您的test模板中应该为type="text/x-handlebars"