Ramiro Tormenta
Ramiro Tormenta

Reputation: 611

How to use _or_ condition in template strings?

I'm creating a project using node.js. I'm using yo-yo library to create html templates.

I want to add a cover from tweet user profile_banner_url.

Like this:

const yo = require('yo-yo')
module.exports = function (tweet) {
  return yo`
    <div class='cover'>
      <img src='${tweet.user.profile_banner_url}' />
    </div>
  `
}

However, sometimes tweets don't return any profile_banner_url, which gives an error in browser.

I tried to add a different image from public directory:

<img src='${tweet.user.profile_banner_url} || otherimg.jpg' />

But it didn't work.

What is the best approache to use or condition in template strings?

Upvotes: 2

Views: 121

Answers (3)

Thomas
Thomas

Reputation: 657

I guess now it's possible to use the nullish coalescing operator like

<img src="${some_url ?? 'publicurl.jpg'}" />

Or a regular ternary

<img src="${some_url !== undefined ? some_url : 'public.jpg'}" />

Upvotes: 1

Thomas
Thomas

Reputation: 657

I found this solution for my case

`<input class="range-slider__slider" type="range" ${ ( (inputType) => {
                  if(inputType == 'temperature')
                    return 'min="-10" max="30" value="23" data-type="' + inputType +'"';
                  else if(inputType == 'light')
                    return 'min="0" max="1000" value="300" data-type="' + inputType +'"';
                  else if(inputType == 'floor')
                    return 'input(type="range" min="0" max="30" value="23" data-type="' + inputType + '"';
                  else
                    return ''
                } )(inputType)}">`

Upvotes: 0

Bergi
Bergi

Reputation: 664579

You're looking for

`<div class='cover'>
  <img src='${tweet.user.profile_banner_url || 'otherimg.jpg'}' />
</div>`

Notice that the part inside the ${} is just a regular javascript expression.

Upvotes: 7

Related Questions