Search code examples
javascriptdust.js

Using dynamic variable names for arrays in dust js


My model looks like:

var model = { 
    tagTypes : ["product", "location"],
    cards : [{
        title : "Card 1",
        product : ["prod1"],
        location : ["US", "UK"]
    },
    {
        title : "Card 2",
        product : ["prod2"],
        location : ["UK"]
    }]
};

I am getting fields (this is a dynamic list & it may change depending on response) for my "card" (i.e. product & location in this case) as an array (tagTypes)

I want to loop through elements of these fields one by one. I am able to get these lists in serialized form using my current dust template. But I want to actually loop through every individual element so that I may add some extra html in between.

Current Dust template :

 {#cards}
    {title} | 
    {#tagTypes card=.}
        {card[.]}
    {/tagTypes}
    <br/>
{/cards}

Current Output :

Card 1 | product: [prod1] location: [US,UK] 
Card 2 | product: [prod2] location: [UK] 

Required output (day) :

Card 1 | product: <span class="tag">prod1</span> location: <span class="tag">US<span> <span class="tag">UK</span> 
Card 2 | product: <span class="tag">prod2</span> location: <span class="tag">UK</span> 

See : http://jsfiddle.net/74nw7dm3/5/ for experimenting with above code.


Solution

  • Problem was due to use of hash and dot together in a single dust tag (which dust doesn't supports)

    To solve this I used a scalar available in my model & created a section with parameter that refers the required key of my object. This eliminated the use of dot operator which allowed me to use hash safely.

    model

    var model = { 
        tagTypes : ["product", "location"],
        garbage : "foo",
        cards : [{
            title : "Card 1",
            product : ["prod1"],
            location : ["US", "UK"],
        },
        {
            title : "Card 2",
            product : ["prod2"],
            location : ["UK"]
        }]
    };
    

    Working template :

    {#cards}
        {title} | 
        {#tagTypes card=.}
           {.}: 
           {#garbage tagType=.}
           {#card[tagType]}
               <span> {.} </span>
           {/card[tagType]}
           {/garbage}
        {/tagTypes}
        <br/>
    {/cards}
    

    Working jsfiddle : http://jsfiddle.net/74nw7dm3/7/