Skip to content Skip to sidebar Skip to footer

How Do I Loop Through An Array Passed Directly To Dust.js?

Using the dust.js javascript templating engine, I want to pass an array directly: var templateContents; //loaded by require.js var compiled = dust.compile(templateContents, 'viewEl

Solution 1:

I'm not sure exactly what was going wrong with one of the things I tried in the original question, but thanks Trevor for pointing this out.

dust.render("viewElements", ["bob", "joe", "sue"], function(err, out){
    $('#view').html(out);
});

This will work with this:

{#.}{.}<br>{/.}

If you've got an array of objects:

dust.render("viewElements", [{name:"bob"}, {name:"joe"}, {name:"sue"}],
    function(err, out){
        $('#view').html(out);
    });

You can render them by referencing the name property on the . element:

{#.}{.name}<br>{/.}

Or directly:

{#.}{name}<br>{/.}

Solution 2:

This answer may be too late :)

This code seems to work for me (passed the array as data object to the template while rendering):

var compiled = dust.compile("{#data}{.}<br>{/data}", "viewElements");
        dust.loadSource(compiled);
        var arr = ["bob", "joe", "sue"];
        dust.render("viewElements", {"data" : arr}, function(err, out){
            $('#content').html(out);
        });

Post a Comment for "How Do I Loop Through An Array Passed Directly To Dust.js?"