A simpler way is to optionally include String in the ES6 string pattern.

I want to display hello username if the condition isLoggedIn is true, and just hello otherwise.

I use ES6 line patterns to try to make the syntax more enjoyable than just concatenating old lines. However, the best way I've found is this ( es6fiddle )

 'hello ${isLoggedIn(false) ? username : ''}' 

This is still not very good syntax, especially in long templates where there is more than one variable with which I want to do this.

I tried to find syntax that included strings, optionally, in condition-based patterns, but I don't think it is. Something like this would be better:

 'hello ${condition && username}' 

But it returns false to the string if the condition is false.

I also tried to insert the truth of the username into the variable itself, that is, have username undefined or null if it does not exist - however, the string template then simply displays undefined or null .

Can anyone recommend a nicer syntax or approach, or is this the first method that I will best do with String patterns?

+8
source share
2 answers

You can use condition && value || "" condition && value || "" , but it's just as awful as a ternary operator.

I think it's best to use a template with tags 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}`); 
+4
source

Returning to this after a while, I think that a more pleasant template, as indicated in the comment and another answer, really completely separates the logic of resolving the variable from the template.

This allows you to get the desired syntax.

 const username = isLoggedIn ? getUsername(): ''; const display = `hello${username && ' ' + username}` 

Or, easier, but combine the spacing / layout of the template with a variable bit.

 const username = isLoggedIn ? ' ' + getUsername() : ''; const display = `hello${username}` 

This is not a one-liner, but in fact in most cases it can be good.

+2
source

Source: https://habr.com/ru/post/1235394/


All Articles