樣板
將樣板字串解讀為 HTML 樣板,可以有效率地渲染到容器並更新。
匯入
import { html } from 'lit';
簽名
html(strings, values): TemplateResult<1>
參數
- strings
TemplateStringsArray
- values
Array<unknown>
詳細資訊
const header = (title: string) => html`<h1>${title}</h1>`;
html
標籤會傳回要渲染為值的 DOM 的描述。它是延遲的,表示在渲染樣板之前不會執行任何操作。渲染時,如果樣板來自與先前渲染結果相同的表達式,則會有效率地更新,而不是取代。
一個哨兵值,表示 ChildPart 完全清除其內容。
匯入
import { nothing } from 'lit';
類型
symbol
詳細資訊
const button = html`${
user.isAdmin
? html`<button>DELETE</button>`
: nothing
}`;
建議使用 nothing
而不是其他假值,因為它在各種表達式綁定上下文中提供一致的行為。在子表達式中,undefined
、null
、''
和 nothing
的行為相同,且不渲染節點。在屬性表達式中,nothing
會移除屬性,而 undefined
和 null
會渲染空字串。在屬性表達式中,nothing
會變成 undefined
。
將值(通常是 lit-html TemplateResult)渲染到容器。
匯入
import { render } from 'lit';
簽名
render(value, container, options?): RootPart
參數
- value
unknown
任何 可渲染的值,通常是由評估樣板標記(如 {@linkcode html} 或 {@linkcode svg})所建立的 {@linkcode TemplateResult}。
- container
HTMLElement | DocumentFragment
要渲染到的 DOM 容器。第一次渲染會將渲染的值附加到容器,如果先前在那裡渲染了相同的結果類型,則後續渲染會有效率地更新渲染的值。
- options?
RenderOptions
請參閱 {@linkcode RenderOptions} 以取得選項文件。
詳細資訊
此範例會在段落標籤內渲染文字 "Hello, Zoe!",並將其附加到容器 document.body
。
import {html, render} from 'lit';
const name = "Zoe";
render(html`<p>Hello, ${name}!</p>`, document.body);
將樣板字串解讀為 SVG 片段,可以有效率地渲染到容器並更新。
匯入
import { svg } from 'lit';
簽名
svg(strings, values): TemplateResult<2>
參數
- strings
TemplateStringsArray
- values
Array<unknown>
詳細資訊
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>`;
svg
標記函式 應僅用於 SVG 片段,或將包含在 <svg>
HTML 元素內的元素。常見的錯誤是在以 svg
標記函式標記的樣板中放置 <svg>
元素。<svg>
元素是 HTML 元素,應在以 html
標記函式標記的樣板中使用。在 LitElement 用法中,從 render()
方法傳回 SVG 片段是無效的,因為 SVG 片段將包含在元素的陰影根中,因此無法在 <svg>
HTML 元素中使用。
用於在將任何值寫入 DOM 之前對其進行清理。這可以用於實施允許和不允許值的安全性原則,以防止 XSS 攻擊。
匯入
import { SanitizerFactory } from 'lit';
類型
(node: Node, name: string, type: "property" | "attribute") => ValueSanitizer
詳細資訊
使用此回呼的一種方法是根據高風險欄位的清單檢查屬性和屬性,並要求寫入這些欄位的值必須是透過建構方式安全的類別的執行個體。Closure 的安全 HTML 類型是這種技術的一種實作方式 ( https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md )。API Only 模式中的 TrustedTypes polyfill 也可作為此技術的基礎 (https://github.com/WICG/trusted-types)。
匯入
import { SVGTemplateResult } from 'lit';
類型
TemplateResult<SVG_RESULT>
樣板標記函式 html
和 svg
的傳回類型。
匯入
import { TemplateResult } from 'lit';
類型
{_$litType$: T, strings: TemplateStringsArray, values: Array<unknown>}
詳細資訊
TemplateResult
物件會保存渲染樣板表達式所需的所有資訊:樣板字串、表達式值和樣板類型 (html 或 svg)。TemplateResult
物件不會自行建立任何 DOM。若要建立或更新 DOM,您需要渲染 TemplateResult
。如需更多資訊,請參閱渲染。