string-template
string-template copied to clipboard
Adding conditional statements
I read about the module and also using it in my nodejs application in the email templates. The only thing I want to ask is how can I add conditional statements in the templates, execute them and then fill in all the values?
Thanks!
There are templating languages that embed conditionals into the language, this isn't one of those libraries, it's just a replacement engine.
If you want to use this library with conditionals then you would conditionally replace a sub-template.
format("{0}, you have {1} unread messages",
getGreetingFor('Robert'),
12
)
// -> Good evening Robert, you have 12 unread messages
function getGreetingFor(name) {
var hour = (new Date()).getHours();
if (hour >= 5 && hour < 12) {
return format("Good morning {0}", name);
} else if (hour >= 12 && hour < 17) {
return format("Good afternoon {0}", name);
} else {
return format("Good evening {0}", name);
}
}