javascripthtmltemplate-strings

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?


Solution

  • 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.