Search code examples
javascriptdust.js

Dynamic Key Name in Dust.js


I'm looking for a way to call a dynamic key in my dust template file, something like

<table> 
{#array1}
<tr>
    {#array2}
    <td>{#array1}{object.#dynAttrName#}{/array1}</td>
    {/array2}

{/array1}
</table>

I would like to access to something like "object.attribute1" where 1 is the id of the current object in {array1}. (array1[n].id)

Thank you for your Help !


Solution

  • It can be done by adding a helper function to the context object:

    Context object:

    {
       get: function (chunk, context, bodies, params) {
           var obj = dust.helpers.tap(params.ofObj, chunk, context);
           var prop = dust.helpers.tap(params.prop, chunk, context);
           return chunk.write(obj[prop]);
       },
    
       a: {
           b: "bbb"
       }
    }
    

    Template

    {#get prop="b" ofObj=a/}
    

    You can try this in linkedin dust tester

    I believe it can also be done defining a global dust helper.