在ES6模板字面量中插入if语句

53

我有一个简单的ajax请求返回一些数据,然后插入到一个模板文字中。我想知道是否可以在模板中插入一个“if”语句?

如果json对象有第5个颜色,则可以添加更多代码行。

  $.ajax({
url: 'http://localhost:8888/ColourCatchr%202/app/search.php'
}).done(function(results){
var res = jQuery.parseJSON(results);
console.log(res);
$.each(res,function(index,result){
  $('.palettes').append(`
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">${result.name}</h3>
      </div>
      <div class="panel-body">
        <div class="col-md-12 colors">
          <div class="color" style=background-color:#${result['color 1']}><h6>${result['color 1']}</h6></div>
          <div class="color" style=background-color:#${result['color 2']}><h6>${result['color 2']}</h6></div>
          <div class="color" style=background-color:#${result['color 3']}><h6>${result['color 3']}</h6></div>
          <div class="color" style=background-color:#${result['color 4']}><h6>${result['color 4']}</h6></div>

          ${if(result['color 5']){
            <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
            }
          }

          <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
          <p>on hover change to translucent background and black text for ecah color</p>
        </div>
      </div>
      <div class="panel-footer">
          <a class="btn btn-info btn-lg" href="update.html?id=${result.id}">Edit</a>
          <a class="btn btn-danger btn-lg">Delete</a>
      </div>
    </div>`
    )
})

})

“如果在模板中插入‘if’语句是否可行?”不可以。你只能在模板字面量中使用表达式。 - Felix Kling
不要在循环中添加标记。这会导致大量不必要的渲染周期,从JS性能的角度来看几乎是最糟糕的事情。使用var rows = $.map(res, function(result){ return ... })先生成所有标记,然后使用$('.palettes').append(rows.join(''))一次性附加所有生成的标记。 - Thomas
@Thomas 感谢您提供的帮助。我刚刚实现了这个功能,确实效果更好! - Chris Hurst
6个回答

113

您需要将逻辑放入函数或使用三元运算符:

`${result['color 5'] ? 'color 5 exists!' : 'color 5 does not exist!'}`

基于评论的附加示例:

`${result['color 5'] ? 
    `<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>` 
: ''}`

1
谢谢!三元运算符完美地工作了,但我只能让它用于返回字符串而不是HTML。抱歉问这么愚蠢的问题,但我错过了什么?我需要转义某些字符吗?为了明确起见,我正在尝试显示以下HTML:<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div> - Chris Hurst
1
我添加了一个额外的示例,对我来说似乎有效(我没有使用jQuery的append方法进行测试)。 - Andy Gaskell
3
非常好!再次感谢。我没有意识到需要再次使用反引号来插入HTML。 - Chris Hurst
@AndyGaskell 喜欢它! - Fred K

29
MDN 关于模板字符串的文章中:
模板文字是允许嵌入表达式的字符串字面量。
所以,您还可以使用 IIFE(立即调用函数表达式)。例如:(() => { ... })()
虽然,我会认为如果你在模板字符串中需要比三元表达式更复杂的逻辑,那么你应该考虑重构你的代码。但是,既然其他答案中还没有提出这种方法,那么这里介绍一种使用 IIFE 的方法。这在情况下很有用,其中三元表达式足够,但是您更喜欢以命令形式阅读您的分支逻辑;或者在将其他多行模板字符串嵌入时使用。
让我为您举个例子:
/* Note: I'm using a tagged template literal for HTML templates here, 
 * similar to the one provided by www.npmjs.com/package/lit-html. 
 */

html`
  <div class="example">
    ${(() => {
      if (result['color 5']) {
        return html`
          <div class="color-preview" style="background-color: ${result['color 5']}"></div>
          <span> Here's your color #5 </span>
        `
      } else {
        return html`<div>You don't have a 5th color</div>`
      }
    })()}
  </div>
`

由于函数体可以包含不止表达式,因此该技术允许您在模板字符串中使用任何JavaScript语法。


如果你选择这条路,请记得 else - 否则你很可能会得到一个 undefined - pusle

6
你可以在模板字面量中使用nullish coalescing运算符。
`${result['color 5'] ?? `Color 5 exists`}`

更好的方法是为函数创建默认参数。
const renderHello = (name = "new member") => `Hello ${name}`;

console.log(1, renderHello());
console.log(2, renderHello("James"));
// 1 Hello new member
// 2 Hello James

1
这实际上是不正确的。如果 result['color 5'] 未定义,字符串文字将呈现为 "undefined"。我的错误。 - etoxin
你可以使用!!result['color 5']将其作为布尔类型进行检查。 - 7urkm3n
即使作为布尔值,你仍然会得到字符串“false”。 - Chase

5

有时候,当条件为 false 时,您可能不想呈现任何内容,就像在问题中所示。因此,您可以这样做:

(注意:当嵌套的模板文字在 ${} 中时,也可以彼此嵌套)

const html = `
  <div>
    <div>
      Lots of HTML stuff
    </div>
    <div>

    ${result['color 5'] && `
      <div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>
    `}
  </div>
`;

这是因为,在Javascript中,与其他语言不同的是,逻辑运算符(&&||) 不一定返回truefalse

逻辑 AND 运算符(&&:

Javascript 返回第一个 falsy 变量,如果没有找到,则返回最后一个 truthy 变量。

逻辑 OR 运算符(||

Javascript 返回第一个 truthy 变量,如果没有找到,则返回最后一个 falsy 变量。

你可以在这里看到它的实际应用:

console.log(true && true) // true
console.log(false && true) // false    
console.log("a" && "b"); // b
console.log(false && "b"); // false
console.log(0 && "b"); // 0
console.log("a" && NaN); // NaN

这在JSX中非常常见。


2
在使用三元运算符时使用变量,可以像这样使用嵌套模板文字

let var1 = 6
let var2 = 8

console.log(`${ `${var1 > var2 ? var1 + ` (var1) `: var2 + ` (var2) `}` } is greater`)


SonarQube不鼓励使用嵌套模板字面量,如果您的代码库中有Sonarqube分析,请避免使用此功能。Sonarqube分析会读取“通过将多个模板字面量嵌套在一起构建复杂的字符串字面量,从而失去可读性和可维护性。在这种情况下,最好将嵌套的模板移到单独的语句中。” - Ganga

0
const heading = 'head';
const location = 'erode';
const district = 'erode';

const isSameLocationDistrict = (location === district) || false;
const storeSlug = `${heading} ${isSameLocationDistrict === true ? location : `${location } ${district}`}`;
console.log(storeSlug);

// "head erode"
// "head erode1 erode"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接