Search code examples
javascripttemplate-literals

How can a template literal be stored unprocessed, so that it can be later passed to a tag function?


Is it possible to create a tag function when the template literal is a variable? e.g. instead of this

render`<h1>Hello World</h1>`

Is there any way to do this?

const template = `<h1>Hello World</h1>`
render(template)

Solution

  • No, that's not possible. Tagged templates are a special syntax where render will get called with a string array and all the ${value} values. By storing it in a variable like that, the template literal is instead interpreted as a regular template literal to be converted to a string instead of a function call.

    Of course, if all your render function does is concatenation of the template and its variables, it doesn't matter. But mind that the variables inside the template literal are already evaluated when you store it in a variable, it can't get re-evaluated later.