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

How to use _or_ condition in template strings?

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

我想添加推文用户 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>
  `
}

但是,有时推文不会 return 任何 profile_banner_url,这会导致浏览器出错。

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

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

但是没有用。

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

您正在寻找

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

请注意 ${} 中的部分只是一个常规 javascript 表达式。

我为我的案例找到了这个解决方案

`<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)}">`