How do I loop through an array passed directly to dust.js?

我与影子孤独终老i 提交于 2019-12-23 15:13:16

问题


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.


回答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>{/.}



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


来源:https://stackoverflow.com/questions/11110049/how-do-i-loop-through-an-array-passed-directly-to-dust-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!