lit-elementlitlit-html

Is there a way to make tags in lit-html templates dynamic?


Question is pretty much self-explanatory.

Example:

function generateTemplate(tag) {
  return html`
    <${tag}
      .some-prop=${1}
    >
      ...
    </${tag}>
  `;
}

Solution

  • There isn't one way to do specifically what you mention here, but there are two approaches that can get you somewhat close:

    const template = tag => { 
      if (tag === 'custom-component') {
        return html`<custom-component></custom-component>`;
      } else if (tag === 'other-component') {
        return html`...`;
      } else {
        return html`<some-default></some-default>`;
      }
    };

    import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';
    const template = unsafeContent => {
      // bear in mind that this should only be done after sanitizing the content
      return html`${unsafeHTML(unsafeContent)}`;
    };
    template('<my-component>Some content</my-component>');