Search code examples
dust.js

Iterate through properties of current context objects in Dust.js


Given the JSON object:

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' } 
}

How do I iterate through the properties of each "current context" object?

I would think you do something like this:

{#errors}
    {#.}
         {type}
    {/.}
{/errors}

Solution

  • It is not possible to iterate through members of an object in Dust. Part of the reason is that you cannot know the order of the members. Another part is that this is seen as bringing too much logic into Dust.

    Instead, you can change the JSON to look more like this:

    {
      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'
        }
      ]
    }