【问题标题】:How to use _or_ condition in template strings?如何在模板字符串中使用 _or_ 条件?
【发布时间】:2017-10-01 10:19:23
【问题描述】:

我正在使用 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>
  `
}

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

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

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

但是没有用。

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

【问题讨论】:

  • 请注意,您可以在 JavaScript 中使用模板字符串,但不能在 HTML 中使用。您的代码看起来像 HTML,但实际上可能在 .js 文件或 &lt;script&gt; 标记中?
  • @ArneHugo Excatly。使用yo-yo 库。是用js制作的模板。我用这个细节编辑了这个问题,谢谢。

标签: javascript html template-strings


【解决方案1】:

你在寻找

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多