2013-02-11 37 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