javascript 如何遍历直接传递给dust.js 的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11110049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I loop through an array passed directly to dust.js?
提问by Will Shaver
Using the dust.js javascript templating engine, I want to pass an array directly:
使用dust.js javascript模板引擎,我想直接传递一个数组:
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]
但似乎无法正确引用数组或其中的元素。第一个例子打印:[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.
我可以命名我传入的每个数组,但我试图避免这样做,因为数组实际上来自主干集合,而且这样做似乎需要额外的工作。
回答by Will Shaver
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.
我不确定我在原始问题中尝试过的其中一件事到底出了什么问题,但感谢 Trevor 指出这一点。
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>{/.}
回答by Saravanan S
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);
});