Search code examples
javascriptdust.js

dust.js - can I use a helper to loop through a comma separated value?


I'm new to dust.js.

one of the values in a JSON object I'm working with is "foo,bar,baz". Can I write a helper to iterate through these values like a # section? Or is there another way to do that without preprocessing the JSON object?

Thanks!


Solution

  • The answer is definetly YES. As logicless templating engine, dust.js handles all logic inside the helpers. In your example it will suffice to just split the value, loop over the values while rendering your content and then return everything at the end of the function.

    EXAMPLE:

    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); 
        });
    }