1

给定 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}
4

3 回答 3

4

如果您确实必须将有意义的数据放入对象键中,请考虑编写上下文帮助器,如下所示:

于 2013-03-08T11:59:34.450 回答
0

在 Dust 中无法遍历对象的成员。部分原因是您无法知道成员的顺序。另一部分是这被视为给 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'
    }
  ]
}
于 2013-03-06T05:59:50.803 回答
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}
于 2015-02-04T17:23:46.280 回答