I want to display hello username if a condition isLoggedIn
is true, and just hello otherwise.
I'm using ES6 String templates to try to make the syntax nicer than plain old string concatenation. However the best way I've found to do it is the following (es6fiddle)
`hello ${isLoggedIn(false) ? username : ''}`
It's still not very nice syntax, particularly in longer templates where there is more than one variable I want to do this with.
I have been trying to find a syntax which includes strings optionally into templates, based on a condition, but I don't think there is one. Something like this would be nicer:
`hello ${condition && username}`
But, it renders false into the String if the condition is false.
I also tried baking the truthiness of username
into the variable itself, i.e. have username
be undefined
or null
if it doesn't exist - however the string template then just renders undefined or null.
Can anyone recommend a nicer syntax, or approach, or is the first method the best I'm going to do with String templates?
You can add new line breaks using the Enter key inside a template string literal. The back tick, “`”, is the upper leftmost key on a standard keyboard.
Template Strings significantly simplify multiline strings. Simply include newlines where they are needed and BOOM. Here's an example: Any whitespace inside of the backtick syntax will also be considered part of the string.
Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.
String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.
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}`);
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