簡體   English   中英

在 ES6 模板文字中插入 if 語句

[英]Inserting if statement inside ES6 template literal

我有一個簡單的 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>`
    )
})

})

您需要將邏輯移動到函數中或使用三元運算符:

`${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>` 
: ''}`

來自關於模板字符串的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 語法。

您可以在模板文字中使用空合並運算符。

`${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

要在使用三元運算符時使用變量,請使用如下嵌套模板文字

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

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"

如果條件為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 中,當您有由&&分隔的條件語句時,返回最后一個條件(如果不滿足任何條件,則返回false )。 或者,如果您使用|| ,返回第一個匹配條件。 你可以在這里看到這個:

 console.log("a" && "b"); console.log(false && "b"); console.log("a" || "b"); console.log(false || "b");

這在 JSX 中非常常用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM