Applecow
Applecow

Reputation: 842

lit-html: concatenating strings to use html``

I am programming a web-component with lit-element and wonder, how I can render a string inside of a variable which still has intact @click listeners with the html "processor" instead of the pure string.

someFunction() {
    var someString=`<button @click="alert('hi')">blah</button>`;
    return html([someString]);
}
render() {
    return this.someFunction();
}

doesn't work, while

someFunction() {
    return html`<button @click="alert('hi')">blah</button>`
}
render() {
    return this.someFunction();
}

works.

Thanks for your help!

Upvotes: 2

Views: 2286

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 20970

That is not possible. These are two tagged template literal and function call fundamentally different things:

Tagged template literal

html`<button @click="alert('hi')">blah</button>`

Calling html as a tagged template function will call html function with n-argument parameters. First will be an array of the constant part of the template and arguments from second onwards will be interpolated valued.

Ordinary function call

const someString = `<button @click="alert('hi')">blah</button>`;
html([someString]);

Calling html as a function html([someString]) will call that function with array as its first argument.

Being a language feature, the browser needs to understand a tagged template from ordinary function. It happens at a lexical/syntactical level and thus a tagged function must and must be followed by backtick(`) character.

In summary, tagged function html cannot exist without backtick. You can read more here on MDN docs.

Upvotes: 3

Related Questions