javascriptweb-componentcustom-elementlit-elementlit-html

Dynamic tags for lit-html not possible?


Can anyone tell me why I cannot use variables within lit-html's html method?

const h1 = 'h1';
return html`
  <${h1} class="a-heading ${classes}">
    <slot></slot>
  </${h1}>
`;

If I replace ${h1} with h1 that works without problems.


Solution

  • For everyone interested in my solution: Use unsafeHTML if you can (you should not do that if you wrap any input fields within).

        import { unsafeHTML } from 'lit-html/directives/unsafe-html';
       
         // ...
    
        const template = `
          <h${this.rank} class="a-heading">
            <slot></slot>
          </h${this.rank}>
        `;
    
        return html`
          ${unsafeHTML(template)}
        `;