我是dust.js的新手。
我正在使用的JSON对象中的一个值是"foo,bar,baz“。我可以编写一个帮助器来像#节一样遍历这些值吗?或者,有没有其他方法可以在不对JSON对象进行预处理的情况下做到这一点?
谢谢!
发布于 2013-04-06 18:57:48
答案绝对是肯定的。作为无逻辑的模板引擎,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);
});
}
https://stackoverflow.com/questions/14805659
复制