mhtml templates

html

The tagged template string function you can use to render any HTML and include variables as part of tag-names, attributes and content.

Check out htmopen in new window and vhtmlopen in new window for more information. Although most examples use JSX, the supported features are pretty much the same.

Basic variables

import { html } from '@muban/template';

const tag = 'p';
const className = 'is-active';
const content = 'hello world';

html`<${tag} class=${className}>${content}</${tag}>`;
1
2
3
4
5
6
7
<p class="is-active">hello world</p>
1

Include partial templates

Just calling the child template function:

const ItemTemplate = ({ label }) => (
  html`<li>${label}</li>`
);

const ListTemplate = ({ items }) => (
  html`<ul>
    ${items.map(item => ItemTemplate(item))}
  </u>`
);
1
2
3
4
5
6
7
8
9

As can be seen, looping over items can just be done using Array.map and returning an array of rendered template strings.

Spreading

Spreading is supported:

html`<p ...${obj}></p>`;
1

Tag component

If the tag variable is a function, it gets called as a "sort of"open in new window "component".

let items = ['one', 'two'];

const Item = ({ item, index, children }) => (
  html`<li id=${index}>
    <h4>${item}</h4>
    ${children}
  </li>`
);

console.log(
  html`<div class="foo">
    <h1>Hi!</h1>
    <ul>
      ${items.map( (item, index) => (
        html`<${Item} ...${{ item, index }}>
          This is item ${item}!
        </${Item}>`
      ))}
    </ul>
  </div>`
);


 
 
 
 
 
 






 
 
 




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

unsafeHTML

declare function unsafeHTML(data: string): string;
1

By default, every variable in the template string is considered unsafe and will be escaped. To opt-out here, we can use the unsafeHTML helper.

import { html, unsafeHTML } from '@muban/muban'

const content = 'Hello <strong>world</strong>!';

html`<div>
  <p>${content}</p>
  <p>${unsafeHTML(content)}</p>
</div>`
1
2
3
4
5
6
7
8
<div>
  <p>Hello &lt;strong&gt;world&lt;/strong&gt;!</p>
  <p>Hello <strong>world</strong>!</p>
</div>
1
2
3
4

Another way to render raw HTML is use the dangerouslySetInnerHTML option from React. In most scenarios this shouldn't be needed, unless you want to add content that is not valid HTML into an element that can render other things (like script tags - see jsonScriptTemplate below).

const content = 'Hello <strong>world</strong>!';

html`<div>
  <p dangerouslySetInnerHTML=${{
    __html: content,
  }}></p>
</div>`
1
2
3
4
5
6
7

jsonScriptTemplate

In muban, it's supported to read component property from a JSON script tag, mostly used when the data is too much to fit nicely into data- attributes.

declare function jsonScriptTemplate(content: Array<any> | Record<string, any>): string;
1

Example

html`<div>${jsonScriptTemplate({ isExpanded: true })}</div>`;
1
<div>
  <script type="application/json">
    { "isExpanded": true }
  </script>
</div>
1
2
3
4
5