5

我有一个 Handlebar 助手来调用模板中的模板,

用法是这样的:

applyTemplate subTemplateId arg1=123 arg2="abc" ...

也可以传递html内容

   {{# applyTemplate "tli" a=1 b="y"}}
   ... any content here will get passed to the sub template with {{content}}
   {{/ applyTemplate }}

这个 jsFiddle 说明了它是如何工作的:http: //jsfiddle.net/maxl/ywUjj/

我的问题:我希望调用范围内的变量可以在子模板中访问,在 jsFiddle 中,请注意 {{topLevelVar}} 是如何不可用的。

谢谢

4

3 回答 3

0

在 topLevelVar 之前添加“../”以访问父上下文。

例如:{{../topLevelVar}}

<script id="tli" type="text/x-handlebars-template">
    <tr><td>{{a}}----> {{content}} <----- {{b}}</td></tr>
</script>

<script id="zaza" type="text/x-handlebars-template">
  <table>
      {{# applyTemplate "tli" a=1 b="y"}}<input type="text" value='a'>{{../topLevelVar}}{{/ applyTemplate }}
    {{# applyTemplate "tli" a=2 b="z"}}<input type="text" value='b'>{{/ applyTemplate }}      
  </table>
</script>
于 2014-08-31T20:51:58.773 回答
0

From this example i would say you can use fn to access the context in your helper method http://yehudakatz.com/2010/09/09/announcing-handlebars-js/

applyTemplate: function(context, fn) {
    for(var i=0, j=context.length; i < j; i++) {
      buffer.push(fn(context[i]))
    }
}

Where fn is the inner "template" part, and context the model that gets applied to it.

于 2013-01-24T14:42:17.893 回答
0

http://jsfiddle.net/dain/NRjUb/上的解决方案开始,我们可以实现相同的结果,但使用内联模板如下:

<script id="topLevel" type="text/x-handlebars-template">
    {{# defTpl "test1"}}
    La plantilla <b>diu</b> {{part}},{{../topLevelVar}}
    {{/ defTpl }}
    {{# each sub }}
    Iplant-->{{eTpl "test1" part=this}}--fi plant<br>
    {{/each}}    
</script>

并注册车把助手,例如:

(function()
{
    var h={};

Handlebars.registerHelper('defTpl', function(name, context){
    // the subtemplate definition is already compiled in context.fn, we store this
    h[name]=context.fn;
    return "";
});

// block level /inline helper
Handlebars.registerHelper('eTpl', function(name, context){
    if (!h[name]) return "Error , template not found"+name;
    var subTemplate =  h[name];
    //if this isn't a block template , the function to render inner content doesn't exists
    var innerContent = context.fn?context.fn(this):"";
    var subTemplateArgs = $.extend({}, context.hash, {content: new Handlebars.SafeString(innerContent)});

    return new Handlebars.SafeString(subTemplate(subTemplateArgs))
});


})();

并调用它:

var _template =  Handlebars.compile($('#topLevel').html());
$('body').append(_template({topLevelVar:123, content:"cascading",sub:[45,30,12]}));

希望这可以帮助 :)

于 2013-07-18T10:55:14.640 回答