javascript - If Else in Dust.js -


my template is

{#results}     {#publisher}publisher label {/publisher}     {#editor}editor label {/editor}     {#author}author label {/author} {/results} 

data is

{     results: {         "publisher": "pankaj",         "editor": "mike",         "writer": "henry"     } } 

it outputs "publisher label editor label "

i want output "publisher label editor label writer". logic being since writer undefined in template should print key itself. how implement logic in template? whole data should printed.

as specified, can't solve problem in dust. have couple options, , elaborate on both.

option 1: change data format

dust iterates on arrays, , iteration logic want here since want @ keys, not ones specified in template.

changing data more this:

{   results: [     { role: "publisher", name: "pankaj" },     { role: "editor", name: "mike" },     { role: "writer", name: "henry" }   ] } 

will allow write template (and require dustjs-helpers):

{#results}   {@select key=role}     {@eq value="publisher"}publisher label{/eq}     {@eq value="editor"}editor label{/eq}     {@eq value="author"}author label{/eq}     {@none}{role}{/none}   {/select} {/results} 

the special {@none} helper outputs if none of other truth tests evaluate true.

option 2: custom dust helper, {@iterate}

you can write helpers extend dust's templating logic. writing helper context easy way extract data need. in case, there's {@iterate} helper that's been written you. use this, after including , dustjs-helpers:

{@iterate key=results}   {@select key=$key}     {@eq value="publisher"}publisher label{/eq}     {@eq value="editor"}editor label{/eq}     {@eq value="author"}author label{/eq}     {@none}{$key}{/none}   {/select} {/iterate} 

although have add helper, if can't reformat data may better option.


Comments