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?
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`
${(() => {
if (result['color 5']) {
return html`
Here's your color #5
`
} else {
return html`You don't have a 5th color`
}
})()}
`
This technique allows you to use any JavaScript syntax "within" your template string