Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, "viewElements");
dust.loadSource(compiled);
dust.render("viewElements", ["bob", "joe", "sue"], function(err, out){
    $('#view').html(out);
});

How do I create a template file to handle an array directly? I've tried a number of things including:

{.}<br>

and

{#.}
 {.}
{/.}

But can't seem to reference the array or the elements in it correctly. The first example prints: [object Object]

I could name each array that I pass in, but what I'm trying to avoid having to do that as the arrays are actually coming from backbone collections and it seems like extra work to do so.

like image 977
Will Shaver Avatar asked Dec 12 '22 01:12

Will Shaver


1 Answers

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>{/.}
like image 131
Will Shaver Avatar answered Dec 26 '22 10:12

Will Shaver