1

私はdust.jsが初めてです。

私が扱っている JSON オブジェクトの値の 1 つは、「foo、bar、baz」です。# セクションのように、これらの値を繰り返し処理するヘルパーを作成できますか? または、JSON オブジェクトを前処理せずにそれを行う別の方法はありますか?

ありがとう!

4

1 に答える 1

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); 
    });
}
于 2013-04-06T18:57:48.160 に答える