Search code examples
loopsdust.js

Dust.js - Syntax : Define a context for a loop


I'm learning the syntax of DustJS with the Getting Start of the documentation, and I'm trying to create a loop. Here is my data (from a MongoDB database):

[{  "name" : "John",
    "mail" : "[email protected]" },
{   "name" : "Tom",
    "mail" : "[email protected]" },
{   "name" : "Pete",
    "mail" : "[email protected]" }]

I would get a result similar to this:

<ul>
    <li>John : [email protected]</li>
    <li>Tom : [email protected]</li>
    <li>Pete : [email protected]</li>
</ul>

So I tried this (and it works):

<ul>
    {#.}<li>{name} : {mail}</li>{~n}{/.}
<ul>

I wonder if defining a context with {#.}{/.} is the best way to achieve this (without that it does not work), it seems to me not clean compared to the doc, what do you think?


Solution

  • That's the way to do it. otherwise declare your context like:

    {names: [
        {name : 'John', mail: '[email protected]'},
        ...
    

    and then update your template to:

    <ul>
        {#names}<li>{name} : {mail}</li>{~n}{/names}
    <ul>