2012-05-10 28 views
5

Tôi có một helper tay lái để gọi một mẫu trong một mẫu,tay lái trợ giúp cho mẫu thành phần

việc sử dụng là:

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

nó cũng có thể để vượt qua nội dung html

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

jsFiddle này minh họa cách hoạt động: http://jsfiddle.net/maxl/ywUjj/

Vấn đề của tôi: Tôi muốn các biến trong phạm vi cuộc gọi có thể truy cập trong bảng phụ, trong jsFiddle, hãy lưu ý cách {{topLevelVar}} không khả dụng.

Cảm ơn

+3

Tôi tìm thấy câu trả lời, xem: http://jsfiddle.net/maxl/2Y9CS/ –

Trả lời

0

Từ ví dụ này tôi sẽ nói rằng bạn có thể sử dụng fn để truy cập nội dung trong phương pháp helper bạn 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])) 
    } 
} 

đâu fn là bên trong "mẫu" phần, và bối cảnh mô hình được áp dụng cho nó.

0

Bắt đầu từ giải pháp trên http://jsfiddle.net/dain/NRjUb/ chúng ta có thể đạt được kết quả tương tự, nhưng với các mẫu nội tuyến như:

<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> 

Và đăng ký tay lái người giúp đỡ như:

(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)) 
}); 


})(); 

Và gọi này với:

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

Hy vọng điều này sẽ giúp :)

0

Thêm "../" trước khi topLevelVar truy cập vào ngữ cảnh gốc.

Ví dụ: {{}} ../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> 
Các vấn đề liên quan