I was trying doT.js
template engine.How to do nested if-else if in dot.js
like
if()
.....
else if
.....
else if
.....
else
.....
The if and if-else statements can be nested, meaning they can be used inside another if or else statement.
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist.
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).
You can do it like this:
<!-- CONDITIONAL !-->
<!-- if -->
<div>
{{? it[0].firstName }}
{{=it[0].firstName }}
{{?}}
</div>
<!-- if / else if / else -->
<div>
<!-- if -->
{{? it[0].lastName }}
<span>First name is set</span>
<!-- else if -->
{{?? it[0].zip}}
<span>You don't have a last name</span>
<!-- else if -->
{{?? it[0].firstName}}
<span>Your firstName is: {{=it[0].firstName}}</span>
<!-- else if end -->
{{??}}
<!-- else -->
<span>You didn't set your name</span>
<!-- if end -->
{{?}}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With