Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicer way to optionally include String in ES6 String template

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?

like image 798
davnicwil Avatar asked Nov 06 '15 19:11

davnicwil


People also ask

How do I add a new line to a string template?

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.

Do template strings support multiline strings?

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.

What is `` in JS?

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.

What is string interpolation in ES6?

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.


2 Answers

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 || ''}" ... />`
like image 140
moose-o Avatar answered Oct 23 '22 11:10

moose-o


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}`);
like image 45
Bergi Avatar answered Oct 23 '22 09:10

Bergi