Please check the full documentation.
This library makes use of:
- htm that provides a jsx-like syntax as tagged template
string and convert it to JSX/Hyperscript to render it with
vhtml. - vhtml that renders parsed JSX/Hypertext to a string.
- eslint-plugin-lit and eslint-plugin-lit-a11y for linting support.
The main purpose of this library is to use together with @muban/muban while developing
components before it's integrated on the server to be previewed in storybook, or when rendering
static pages.
Add @muban/template to your project:
yarn add @muban/templateCreate our template:
import { html } from "@muban/template";
type MyComponentProps = {
welcomeText: string;
};
function myComponentTemplate({ welcomeText }: MyComponentProps, ref?: string) {
return html`
<div data-component="my-component" data-ref=${ref}>
${welcomeText}
</div>
`;
}html– the tagged template string, the core of this library.unsafeHTML– to render any "HTML content" coming from an API (that you trust) – doesn't work with html entities or the<content character.jsonScriptTemplate– a helper function that renders a JSON script tag for an object that can be used instead of a lot of different data attributes, or to use objects as props.ComponentTemplate– atypefor a Muban Template Function.ComponentTemplateResult– atypefor the Template result (to be consumed by other code).TemplateMap– a helper type to extract the "props type" out of a template function as part of a Record of templates, and formats them to be used in a name/props data structure.
By default, the template compiler will escape any special characters into html entities when rendered, so they display as such on the screen;
html`<span>"</span>`;is rendered as
<span>"</span>However, this doesn't work for the < character, since it will mess up the template parser.
Besides that, it's common practise to user html entities in your content;
html`<span>"</span>`;unfortunately this is double encoded now;
<span>&quot;</span>To work around this, we can use the dangerouslySetInnerHTML escape hatch;
html`<span dangerouslySetInnerHTML=${{ __html: '"' }}></span>`;which properly renders as
<span>"</span>Use this to render any html content that you trust (e.g. coming from CMS with sanitized output).
HTML data- attributes with false values will be stringified in the resulting HTML
html`<div data-test=${false}>foo</div>`Will become
<div data-test="false">foo</div>This only will happen for data attributes (attributes that start with data-)
html`<div data-test=${false} another-attribute=${false}>foo</div>`Will become
<div data-test="false">foo</div>Non data attributes with a false value will be ignored in the resulting HTML