doT.js: chained if-else if in dot.js

Manish Kumar picture Manish Kumar · Feb 14, 2014 · Viewed 13k times · Source

I was trying doT.js template engine.How to do nested if-else if in dot.js like

if()
 .....
else if
 .....
else if
 .....
else
 .....

Answer

BenM picture BenM · Feb 14, 2014

You can use the following syntax:

{{? it.name }}
<div>Oh, I love your name, {{=it.name}}!</div>
{{?? it.age === 0}}
<div>Guess nobody named you yet!</div>
{{?? it.age > 20}}
<div>You're old!</div>
{{??}}
You are {{=it.age}} and still don't have a name?
{{?}}

The above gets compiled to:

function anonymous(it /**/) 
{ 
    var out='';

    if(it.name)
    {
        out+='<div>Oh, I love your name, '+(it.name)+'!</div>';
    }
    else if(it.age === 0)
    {
        out+='<div>Guess nobody named you yet!</div>';
    }
    else if(it.age > 20)
    {
        out+='<div>You\'re old!</div>';
    }
    else
    {
        out+='You are '+(it.age)+' and still don\'t have a name?';
    }
    return out; 
}

Essentially, just keep adding {{?? condition}} until you get to {{?}} (the end of the block).