如何在模板字符串中使用_or_ condition?

Ram*_*nta 1 html javascript template-strings

我正在使用node.js创建一个项目.我正在使用yo-yo库来创建html模板.

我想从tweet用户profile_banner_url添加一个封面.

像这样:

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

但是,有时推文不会返回任何profile_banner_url,这会在浏览器中出错.

我试图从public目录中添加不同的图像:

<img src='${tweet.user.profile_banner_url} || otherimg.jpg' />
Run Code Online (Sandbox Code Playgroud)

但它没有用.

or在模板字符串中使用条件的最佳方法是什么?

Ber*_*rgi 7

您正在寻找

`<div class='cover'>
  <img src='${tweet.user.profile_banner_url || 'otherimg.jpg'}' />
</div>`
Run Code Online (Sandbox Code Playgroud)

请注意,${... 内的部分}只是一个常规的javascript表达式.