Inserting if statement inside ES6 template literal

后端 未结 5 1806
慢半拍i
慢半拍i 2021-02-01 16:15

I have a simple ajax request returning some data and then inserting into a template literal. I was wondering if it it possible to insert an \'if\' statement inside the template?

相关标签:
5条回答
  • 2021-02-01 16:26

    To use a variable while using the ternary operator, use a nested template literal like this:

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

    0 讨论(0)
  • 2021-02-01 16:40

    You'll need to move your logic into a function or use the ternary operator:

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

    Additional example based on comment:

    `${result['color 5'] ? 
        `<div class="color" style=background-color:#${result['color 5']}><h6>${result['color 5']}</h6></div>` 
    : ''}`
    
    0 讨论(0)
  • 2021-02-01 16:41

    From the MDN article on template strings:

    Template literals are string literals allowing embedded expressions.

    I would argue that if you need more complicated logic than a ternary expression within your template strings, you should consider refactoring your code. However, since this hasn't been presented by the other answers here, you can also use an IIFE (immediately invoked function expression). This can be useful even in cases where a ternary expression would suffice anyway, solely to make your branching logic clear, especially in cases where you're embedding other multi-line template strings.

    Let me make up an example for you:

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

    This technique allows you to use any JavaScript syntax "within" your template string

    0 讨论(0)
  • 2021-02-01 16:49

    you can also do this

    `${result['color 5'] && `Color 5 exists`}`
    
    0 讨论(0)
  • 2021-02-01 16:49
    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"
    
    0 讨论(0)
提交回复
热议问题