lit-html
- Version 3.2.1
- Published
- 1.71 MB
- 1 dependency
- BSD-3-Clause license
Install
npm i lit-html
yarn add lit-html
pnpm add lit-html
Overview
HTML templates literals in JavaScript
Index
Variables
Functions
Classes
Interfaces
Type Aliases
Namespaces
Variables
variable ATTRIBUTE_PART
const ATTRIBUTE_PART: number;
variable BOOLEAN_ATTRIBUTE_PART
const BOOLEAN_ATTRIBUTE_PART: number;
variable CHILD_PART
const CHILD_PART: number;
variable COMMENT_PART
const COMMENT_PART: number;
variable ELEMENT_PART
const ELEMENT_PART: number;
variable EVENT_PART
const EVENT_PART: number;
variable HTML_RESULT
const HTML_RESULT: number;
TemplateResult types
variable MATHML_RESULT
const MATHML_RESULT: number;
variable noChange
const noChange: Symbol;
A sentinel value that signals that a value was handled by a directive and should not be written to the DOM.
variable nothing
const nothing: Symbol;
A sentinel value that signals a ChildPart to fully clear its content.
const button = html`${user.isAdmin? html`<button>DELETE</button>`: nothing}`;Prefer using
nothing
over other falsy values as it provides a consistent behavior between various expression binding contexts.In child expressions,
undefined
,null
,''
, andnothing
all behave the same and render no nodes. In attribute expressions,nothing
_removes_ the attribute, whileundefined
andnull
will render an empty string. In property expressionsnothing
becomesundefined
.
variable PROPERTY_PART
const PROPERTY_PART: number;
variable render
const render: { ( value: unknown, container: HTMLElement | DocumentFragment, options?: RenderOptions ): RootPart; setSanitizer: (newSanitizer: SanitizerFactory) => void; createSanitizer: SanitizerFactory; _testOnlyClearSanitizerFactoryDoNotCallOrElse: () => void;};
Renders a value, usually a lit-html TemplateResult, to the container.
This example renders the text "Hello, Zoe!" inside a paragraph tag, appending it to the container
document.body
.import {html, render} from 'lit';const name = "Zoe";render(html`<p>Hello, ${name}!</p>`, document.body);Parameter value
Any [renderable value](https://lit.dev/docs/templates/expressions/#child-expressions), typically a created by evaluating a template tag like or .
Parameter container
A DOM container to render to. The first render will append the rendered value to the container, and subsequent renders will efficiently update the rendered value if the same result type was previously rendered there.
Parameter options
See for options documentation.
See Also
variable SVG_RESULT
const SVG_RESULT: number;
Functions
function html
html: (strings: TemplateStringsArray, ...values: unknown[]) => TemplateResult<1>;
Interprets a template literal as an HTML template that can efficiently render to and update a container.
const header = (title: string) => html`<h1>${title}</h1>`;The
html
tag returns a description of the DOM to render as a value. It is lazy, meaning no work is done until the template is rendered. When rendering, if a template comes from the same expression as a previously rendered result, it's efficiently updated instead of replaced.
function mathml
mathml: ( strings: TemplateStringsArray, ...values: unknown[]) => TemplateResult<3>;
Interprets a template literal as MathML fragment that can efficiently render to and update a container.
const num = mathml`<mn>1</mn>`;const eq = html`<math>${num}</math>`;The
mathml
*tag function* should only be used for MathML fragments, or elements that would be contained **inside** a<math>
HTML element. A common error is placing a<math>
*element* in a template tagged with themathml
tag function. The<math>
element is an HTML element and should be used within a template tagged with the tag function.In LitElement usage, it's invalid to return an MathML fragment from the
render()
method, as the MathML fragment will be contained within the element's shadow root and thus not be properly contained within a<math>
HTML element.
function resolveDirective
resolveDirective: ( part: ChildPart | AttributePart | ElementPart, value: unknown, parent?: DirectiveParent, attributeIndex?: number) => unknown;
function svg
svg: (strings: TemplateStringsArray, ...values: unknown[]) => TemplateResult<2>;
Interprets a template literal as an SVG fragment that can efficiently render to and update a container.
const rect = svg`<rect width="10" height="10"></rect>`;const myImage = html`<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">${rect}</svg>`;The
svg
*tag function* should only be used for SVG fragments, or elements that would be contained **inside** an<svg>
HTML element. A common error is placing an<svg>
*element* in a template tagged with thesvg
tag function. The<svg>
element is an HTML element and should be used within a template tagged with the tag function.In LitElement usage, it's invalid to return an SVG fragment from the
render()
method, as the SVG fragment will be contained within the element's shadow root and thus not be properly contained within an<svg>
HTML element.
Classes
class AttributePart
class AttributePart implements Disconnectable {}
constructor
constructor( element: HTMLElement, name: string, strings: readonly string[], parent: Disconnectable, options: RenderOptions);
property element
readonly element: HTMLElement;
property name
readonly name: string;
property options
readonly options: RenderOptions;
property strings
readonly strings?: readonly string[];
If this attribute part represents an interpolation, this contains the static strings of the interpolation. For single-value, complete bindings, this is undefined.
property tagName
readonly tagName: string;
property type
readonly type: 1 | 3 | 4 | 5;
class BooleanAttributePart
class BooleanAttributePart extends AttributePart {}
property type
readonly type: number;
class ChildPart
class ChildPart implements Disconnectable {}
constructor
constructor( startNode: ChildNode, endNode: ChildNode, parent: ChildPart | TemplateInstance, options: RenderOptions);
property endNode
readonly endNode: Node;
The part's trailing marker node, if any. See
.parentNode
for more information.
property options
readonly options: RenderOptions;
property parentNode
readonly parentNode: Node;
The parent node into which the part renders its content.
A ChildPart's content consists of a range of adjacent child nodes of
.parentNode
, possibly bordered by 'marker nodes' (.startNode
and.endNode
).- If both
.startNode
and.endNode
are non-null, then the part's content consists of all siblings between.startNode
and.endNode
, exclusively.- If
.startNode
is non-null but.endNode
is null, then the part's content consists of all siblings following.startNode
, up to and including the last child of.parentNode
. If.endNode
is non-null, then.startNode
will always be non-null.- If both
.endNode
and.startNode
are null, then the part's content consists of all child nodes of.parentNode
.
property startNode
readonly startNode: Node;
The part's leading marker node, if any. See
.parentNode
for more information.
property type
readonly type: number;
class ElementPart
class ElementPart implements Disconnectable {}
constructor
constructor(element: Element, parent: Disconnectable, options: RenderOptions);
property element
element: Element;
property options
options: RenderOptions;
property type
readonly type: number;
class EventPart
class EventPart extends AttributePart {}
constructor
constructor( element: HTMLElement, name: string, strings: readonly string[], parent: Disconnectable, options: RenderOptions);
property type
readonly type: number;
method handleEvent
handleEvent: (event: Event) => void;
class PropertyPart
class PropertyPart extends AttributePart {}
property type
readonly type: number;
class TemplateInstance
class TemplateInstance implements Disconnectable {}
An updateable instance of a Template. Holds references to the Parts used to update the template instance.
constructor
constructor(template: Template, parent: ChildPart);
property parentNode
readonly parentNode: Node;
Interfaces
interface CompiledTemplate
interface CompiledTemplate extends Omit<Template, 'el'> {}
interface CompiledTemplateResult
interface CompiledTemplateResult {}
A TemplateResult that has been compiled by @lit-labs/compiler, skipping the prepare step.
property ['_$litType$']
['_$litType$']: CompiledTemplate;
property values
values: unknown[];
interface DirectiveParent
interface DirectiveParent {}
interface Disconnectable
interface Disconnectable {}
interface RenderOptions
interface RenderOptions {}
Object specifying options for controlling lit-html rendering. Note that while
render
may be called multiple times on the samecontainer
(andrenderBefore
reference node) to efficiently update the rendered content, only the options passed in during the first render are respected during the lifetime of renders to that uniquecontainer
+renderBefore
combination.
property creationScope
creationScope?: { importNode(node: Node, deep?: boolean): Node;};
Node used for cloning the template (
importNode
will be called on this node). This controls theownerDocument
of the rendered DOM, along with any inherited context. Defaults to the globaldocument
.
property host
host?: object;
An object to use as the
this
value for event listeners. It's often useful to set this to the host component rendering a template.
property isConnected
isConnected?: boolean;
The initial connected state for the top-level part being rendered. If no
isConnected
option is set,AsyncDirective
s will be connected by default. Set tofalse
if the initial render occurs in a disconnected tree andAsyncDirective
s should seeisConnected === false
for their initial render. Thepart.setConnected()
method must be used subsequent to initial render to change the connected state of the part.
property renderBefore
renderBefore?: ChildNode | null;
A DOM node before which to render content in the container.
interface RootPart
interface RootPart extends ChildPart {}
A top-level
ChildPart
returned fromrender
that manages the connected state ofAsyncDirective
s created throughout the tree below it.
method setConnected
setConnected: (isConnected: boolean) => void;
Sets the connection state for
AsyncDirective
s contained within this root ChildPart.lit-html does not automatically monitor the connectedness of DOM rendered; as such, it is the responsibility of the caller to
render
to ensure thatpart.setConnected(false)
is called before the part object is potentially discarded, to ensure thatAsyncDirective
s have a chance to dispose of any resources being held. If aRootPart
that was previously disconnected is subsequently re-connected (and itsAsyncDirective
s should re-connect),setConnected(true)
should be called.Parameter isConnected
Whether directives within this tree should be connected or not
Type Aliases
type HTMLTemplateResult
type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;
type MathMLTemplateResult
type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;
type MaybeCompiledTemplateResult
type MaybeCompiledTemplateResult<T extends ResultType = ResultType> = | UncompiledTemplateResult<T> | CompiledTemplateResult;
This is a template result that may be either uncompiled or compiled.
In the future, TemplateResult will be this type. If you want to explicitly note that a template result is potentially compiled, you can reference this type and it will continue to behave the same through the next major version of Lit. This can be useful for code that wants to prepare for the next major version of Lit.
type Part
type Part = | ChildPart | AttributePart | PropertyPart | BooleanAttributePart | ElementPart | EventPart;
type SanitizerFactory
type SanitizerFactory = ( node: Node, name: string, type: 'property' | 'attribute') => ValueSanitizer;
Used to sanitize any value before it is written into the DOM. This can be used to implement a security policy of allowed and disallowed values in order to prevent XSS attacks.
One way of using this callback would be to check attributes and properties against a list of high risk fields, and require that values written to such fields be instances of a class which is safe by construction. Closure's Safe HTML Types is one implementation of this technique ( https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md). The TrustedTypes polyfill in API-only mode could also be used as a basis for this technique (https://github.com/WICG/trusted-types).
Parameter node
The HTML node (usually either a #text node or an Element) that is being written to. Note that this is just an exemplar node, the write may take place against another instance of the same class of node.
Parameter name
The name of an attribute or property (for example, 'href').
Parameter type
Indicates whether the write that's about to be performed will be to a property or a node. A function that will sanitize this class of writes.
type SVGTemplateResult
type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;
type TemplateResult
type TemplateResult<T extends ResultType = ResultType> = UncompiledTemplateResult<T>;
The return type of the template tag functions, and .
A
TemplateResult
object holds all the information about a template expression required to render it: the template strings, expression values, and type of template (html or svg).TemplateResult
objects do not create any DOM on their own. To create or update DOM you need to render theTemplateResult
. See [Rendering](https://lit.dev/docs/components/rendering) for more information.In Lit 4, this type will be an alias of MaybeCompiledTemplateResult, so that code will get type errors if it assumes that Lit templates are not compiled. When deliberately working with only one, use either or explicitly.
type UncompiledTemplateResult
type UncompiledTemplateResult<T extends ResultType = ResultType> = { ['_$litType$']: T; strings: TemplateStringsArray; values: unknown[];};
The return type of the template tag functions, and when it hasn't been compiled by @lit-labs/compiler.
A
TemplateResult
object holds all the information about a template expression required to render it: the template strings, expression values, and type of template (html or svg).TemplateResult
objects do not create any DOM on their own. To create or update DOM you need to render theTemplateResult
. See [Rendering](https://lit.dev/docs/components/rendering) for more information.
type ValueSanitizer
type ValueSanitizer = (value: unknown) => unknown;
A function which can sanitize values that will be written to a specific kind of DOM sink.
See SanitizerFactory.
Parameter value
The value to sanitize. Will be the actual value passed into the lit-html template literal, so this could be of any type. The value to write to the DOM. Usually the same as the input value, unless sanitization is needed.
Namespaces
namespace LitUnstable
namespace LitUnstable {}
Contains types that are part of the unstable debug API.
Everything in this API is not stable and may change or be removed in the future, even on patch releases.
namespace LitUnstable.DebugLog
namespace LitUnstable.DebugLog {}
When Lit is running in dev mode and
window.emitLitDebugLogEvents
is true, we will emit 'lit-debug' events to window, with live details about the update and render lifecycle. These can be useful for writing debug tooling and visualizations.Please be aware that running with window.emitLitDebugLogEvents has performance overhead, making certain operations that are normally very cheap (like a no-op render) much slower, because we must copy data and dispatch events.
interface BeginRender
interface BeginRender {}
interface CommitAttribute
interface CommitAttribute {}
interface CommitBooleanAttribute
interface CommitBooleanAttribute {}
interface CommitEventListener
interface CommitEventListener {}
property addListener
addListener: boolean;
property element
element: Element;
property kind
kind: 'commit event listener';
property name
name: string;
property oldListener
oldListener: unknown;
property options
options: RenderOptions | undefined;
property removeListener
removeListener: boolean;
property value
value: unknown;
interface CommitNode
interface CommitNode {}
interface CommitNothingToChildEntry
interface CommitNothingToChildEntry {}
interface CommitProperty
interface CommitProperty {}
interface CommitText
interface CommitText {}
interface CommitToElementBinding
interface CommitToElementBinding {}
interface EndRender
interface EndRender {}
interface SetPartValue
interface SetPartValue {}
property kind
kind: 'set part';
property part
part: Part;
property templateInstance
templateInstance: TemplateInstance;
property value
value: unknown;
property valueIndex
valueIndex: number;
property values
values: unknown[];
interface TemplateInstantiated
interface TemplateInstantiated {}
property fragment
fragment: Node;
property instance
instance: TemplateInstance;
property kind
kind: 'template instantiated';
property options
options: RenderOptions | undefined;
property parts
parts: Array<Part | undefined>;
property template
template: Template | CompiledTemplate;
property values
values: unknown[];
interface TemplateInstantiatedAndUpdated
interface TemplateInstantiatedAndUpdated {}
property fragment
fragment: Node;
property instance
instance: TemplateInstance;
property kind
kind: 'template instantiated and updated';
property options
options: RenderOptions | undefined;
property parts
parts: Array<Part | undefined>;
property template
template: Template | CompiledTemplate;
property values
values: unknown[];
interface TemplatePrep
interface TemplatePrep {}
property clonableTemplate
clonableTemplate: HTMLTemplateElement;
property kind
kind: 'template prep';
property parts
parts: TemplatePart[];
property strings
strings: TemplateStringsArray;
property template
template: Template;
interface TemplateUpdating
interface TemplateUpdating {}
type CommitPartEntry
type CommitPartEntry = | CommitNothingToChildEntry | CommitText | CommitNode | CommitAttribute | CommitProperty | CommitBooleanAttribute | CommitEventListener | CommitToElementBinding;
type Entry
type Entry = | TemplatePrep | TemplateInstantiated | TemplateInstantiatedAndUpdated | TemplateUpdating | BeginRender | EndRender | CommitPartEntry | SetPartValue;
Package Files (1)
Dependencies (1)
Dev Dependencies (5)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/lit-html
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/lit-html)
- HTML<a href="https://www.jsdocs.io/package/lit-html"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4580 ms. - Missing or incorrect documentation? Open an issue for this package.