给定JSON对象:
errors =
{
hashed_password: {
message: 'Validator "Password cannot be blank" failed for path hashed_password',
name: 'ValidatorError',
path: 'hashed_password',
type: 'Password cannot be blank' },
username: {
message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank' },
email: {
message: 'Validator "Email cannot be blank" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email cannot be blank' },
name: {
message: 'Validator "Name cannot be blank" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'Name cannot be blank' }
}
如何遍历每个“当前上下文”对象的属性?
我认为你会这样做:
{#errors}
{#.}
{type}
{/.}
{/errors}
答案 0 :(得分:4)
如果您真的必须将有意义的数据放入对象键,请考虑编写上下文帮助器,如下所示:
答案 1 :(得分:0)
无法在Dust中迭代对象的成员。部分原因是您无法了解成员的顺序。另一部分是,这被视为给尘埃带来了太多的逻辑。
相反,您可以将JSON更改为更像这样:
{
errors: [
{
hashed_password: {
message: 'Validator "Password cannot be blank" failed for path hashed_password',
name: 'ValidatorError',
path: 'hashed_password',
type: 'Password cannot be blank'
}
},
{
username: {
message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank'
}
},
{
email: {
message: 'Validator "Email cannot be blank" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email cannot be blank'
}
},
{
name: {
message: 'Validator "Name cannot be blank" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'Name cannot be blank'
}
]
}
答案 2 :(得分:0)
您可以使用帮助程序迭代对象。
例如,你可以像这样定义一个帮助器:
dust.helpers.iter = function(chunk, context, bodies, params) {
var obj = dust.helpers.tap(params.obj, chunk, context);
var iterable = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = obj[key];
iterable.push({
'$key': key,
'$value': value,
'$type': typeof value
});
}
}
return chunk.section(iterable, context, bodies);
};
然后,在你的模板中,你会像这样循环:
{@iter obj=errors}
{$value.type}
{/iter}