2013-02-11 36 views

回答

5

答案是肯定的。 作爲無邏輯的模板引擎,dust.js處理幫助器中的所有邏輯。 在你的例子中,只需將值分割,在渲染內容時遍歷值並在函數結尾處返回所有內容就足夠了。

例:

function($, dust) { 
    // helpers object 
    var helpers = { 
     'h_value' : function(chunk, ctx, bodies, params) { 
      var values = ctx.current() 
          .value 
          .split(','); 

      for (var i = 0, l = values.length; i < l; i++) { 
       chunk.write('<li>'+ values[i] +'</li>'); 
      }     
     } 
    } 

    // create a new base context 
    // helpers will be part of context now 
    var base = dust.makeBase(helpers); 

    // this is only an example, you should work with a separate template file  
    var source = '{#sections}<ul>{#h_value}<li>{.}</li>{/h_value}</ul>{/sections}'; 
    // and template should be compiled on server side (in most cases) 
    var compiled = dust.compile(source, 'test'); 
    dust.loadSource(compiled); 

    var sectionsData = { 
     sections : [ 
      { value : 'foo,bar,baz'}, 
      { value : 'bar,baz,foo'}, 
      { value : 'baz,foo,bar'} 
     ] 
    }; 

    dust.render('test', base.push(sectionsData), function(err, content) { 
     $('body').append(content); 
    }); 
} 
+0

這將會是有益的,其實。我想我基本不確定如何寫我自己的助手。 – Murph 2013-04-15 15:13:09

+0

我現在很忙,但我會盡快發佈一個簡單的例子。敬請關注! – op1ekun 2013-04-16 15:09:48

+0

你在這裏:)我盡力了。還有一條建議嘗試徹底閱讀http://akdubya.github.io/dustjs/。這並不完美,但它在開始時會有所幫助:)處理助手的最佳方法是嘗試使用塊,ctx,主體和各種輸出。那很簡單。玩得開心,不要忘記接受我的答案;) – op1ekun 2013-04-18 07:08:43