To declare a text node in a template, use a plain JavaScript string.
Text nodes don't need to be encoded and can safely be passed untrusted text data.
"Hello & Goodbye World", text child node
To include raw HTML text, use the html
directive
to mark the text as HTML.
This example requires escaping on the ampersand (&
) and uses embedded
formatting elements (<em>
):
html("Hello & Goodbye <em>World</em>"),
A callback function can be used to provide dynamic text:
() => new Date().toString(), dynamic text content
For dynamic HTML, wrap either the callback itself in the html()
directive
or just the return value
// this
html(c => c.getHtml())
// or this:
c => html(c.getHtml())
eg:
html(() => `<strong>${htmlEncode(new Date().toString())}</strong>`),
Never use the html()
method with untrusted data. html()
inserts
the passed text directly into the document - malicious scripts included.
To mix untrusted data with HTML content it's usually best to express
the HTML using template nodes explicitly rather than using the html()
directive.
{
type: "em",
text: c => c.untrustedData
}
If you really must mix the html()
directive and untrusted data,
use the htmlEncode
function to escape the untrusted data:
html(c => `<em>${htmlEncode(c.untrustedData)}</em>`),
HTML elements also have a text
property that can be used to directly assign
the inner text or HTML of an element.
See Inner Text/HTML for more on this.
Templates don't include any whitespace between HTML elements.
Usually this doesn't matter, but when it does, simply include the spaces in the template:
{
type: "div",
$: [
// Without spaces, these buttons would have no
// gaps between them
{ type: "button", text: "Button 1" },
" ",
{ type: "button", text: "Button 2" },
" ",
{ type: "button", text: "Button 3" },
]
}
To create HTML comments use the special type #comment
.
{
type: "#comment",
text: "this is a comment",
}
which produces:
<!-- this is a comment -->
As usual, the text
can be dynamic:
{
type: "#comment",
text: c => `rendered at ${new Date().toLocalTimeString()}`,
}
Although rarely used, the comment node can be used for diagnostics and is also occassionally useful with server-side rendering (SSR).