Dust iterate over array

226 Views Asked by At

I am using Kraken.js, dust, mongoose. I have the following object that I get from MongoDB with mongoose.

artist = {
    "_id" : ObjectId("xxxxxxxx"),
    "first_name" : "myName",
    "last_name" : "myLastname",
    "description" : "Sample Description here",
    "thumbnail" : "thumbnail.jpg",
    "works" : [ 
        "art1.jpg", 
        "art2.jpg"
    ]
}

The name of the whole model I send to my template is artist (singular).

I want to generate image tag for each member of works.

<img src="art1.jpg" />
<img src="art2.jpg" />

I have tried following snippets and it's not working

{#.}
    <img src="./../../images/artists/{.works}" alt="" />
{/.}

{#artist.works}
    <img src="./../../images/artists/{.works}" alt="" />
{/.artist.works}

and it prints " "

Genuinely appreciate your help

1

There are 1 best solutions below

7
thefourtheye On BEST ANSWER

TL/DR:

  1. If the context being passed is the artist object, then you need to iterate the works object only.
  2. If the context being passed is an object which contains the artist object, then you need to iterate with artist.works.

This is the working version of your example.

var data = {
  "artist": {
    "first_name": "myName",
    "last_name": "myLastname",
    "description": "Sample Description here",
    "thumbnail": "thumbnail.jpg",
    "works": [
      "art1.jpg",
      "art2.jpg"
    ]
  }
};

var compiled = dust.compile('<ul>{#artist.works}<li><a href="{.}" >{.}</a></li>{/artist.works}</ul>', 'hello');
// Register the template with Dust
dust.loadSource(compiled);
// Render the template
dust.render('hello', data, function(err, out) {
  // `out` contains the rendered output.
  document.getElementById('output').innerHTML = out;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/dustjs-linkedin/2.7.5/dust-full.js"></script>

<div id="output" />