Mur*_*rph 1 javascript dust.js
我是dust.js的新手.
我正在使用的JSON对象中的一个值是"foo,bar,baz".我可以写一个助手来迭代这些值,比如#section吗?或者有没有其他方法可以在不预处理JSON对象的情况下执行此操作?
谢谢!
答案肯定是肯定的.作为无逻辑模板引擎,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);
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1530 次 |
| 最近记录: |