Inserting if statement inside ES6 template literal

后端 未结 5 1815
慢半拍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条回答
  •  闹比i
    闹比i (楼主)
    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'] ? 
        `
    ${result['color 5']}
    ` : ''}`

提交回复
热议问题