Nicer way to optionally include String in ES6 String template
For those of you that landed here by googling something like "print variable in template literal if not null", this might help:
html = `<input type="text" placeholder="${data.placeholder || ''}" ... />`
You can use condition && value || ""
, but that's about as horrible as the ternary operator.
I guess your best bet is to use a tagged template here that discards empty values:
function nonEmpty(parts) {
var res = parts[0];
for (var i=1; i<parts.length; i++) {
if (arguments[i]) // you might want to handle `0` different
res += arguments[i];
res += parts[i];
}
return res;
}
console.log(nonEmpty`hello ${mockIsLoggedIn(false) && username}`);
Coming back to this after a while, I think the nicer pattern as alluded to in the comment and other answer is indeed to completely separate the logic of resolving the variable from the template.
That allows you to get the desired syntax.
const username = isLoggedIn ? getUsername(): '';
const display = `hello${username && ' ' + username}`
Or, simpler, but conflating the spacing/layout of the template with the variable a bit..
const username = isLoggedIn ? ' ' + getUsername() : '';
const display = `hello${username}`
It's not a one-liner, but actually in most cases that's likely to be a good thing.