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

1

1

Question is pretty much self-explanatory.

Example:

function generateTemplate(tag) {
  return html`
    <${tag}
      .some-prop=${1}
    >
      ...
    </${tag}>
  `;
}
Polyphyletic answered 10/12, 2019 at 2:36 Comment(2)
Related issues in lit-html repo: github.com/Polymer/lit-html/issues/217Denbighshire
Does this answer your question? Dynamic tags for lit-html not possible?Providential
P
4

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

  • Conditional rendering

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>');
Pelkey answered 10/12, 2019 at 5:40 Comment(1)
Yeah, was already doing the same thing as conditional rendering via switch cases but there's just too many and it's basically the same properties for each anyway. Could probably work with the unsafeHTML directive but need to sanitize the items set to the props like you said. Hmm.Polyphyletic

© 2022 - 2024 — McMap. All rights reserved.