CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lit-html

HTML templates literals in JavaScript that enable efficient, expressive HTML templating with incremental DOM updates

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

static-templates.mddocs/

Static Templates

Optimization system for templates with static parts that don't change, enabling better performance and smaller bundle sizes through compile-time optimizations.

Capabilities

Static Value Creation

literal Function

Creates static values from template literals for compile-time optimization.

/**
 * Tags a string literal so that it behaves like part of the static template
 * strings instead of a dynamic value. Static values can be changed, but they
 * will cause a complete re-render since they effectively create a new template.
 * @param strings - Template strings array
 * @param values - Static values (must be other literal results or unsafeStatic values)
 * @returns StaticValue for use in static templates
 */
function literal(
  strings: TemplateStringsArray,
  ...values: unknown[]
): StaticValue;

Usage Examples:

import { html, literal } from 'lit-html/static.js';

// Static tag names
const tagName = literal`div`;
const template = html`<${tagName}>Content</${tagName}>`;

// Static attribute names
const attrName = literal`data-id`;
const withStaticAttr = html`<span ${attrName}="123">Text</span>`;

// Combining static values
const className = literal`my-class`;
const id = literal`my-id`;
const combined = html`<div class="${className}" id="${id}">Content</div>`;

unsafeStatic Function

Creates static values from raw strings for advanced use cases requiring dynamic static content.

/**
 * Wraps a string so that it behaves like part of the static template
 * strings instead of a dynamic value. Note that this function is unsafe
 * to use on untrusted content, as it will be directly parsed into HTML.
 * @param value - String to treat as static (must be trusted)
 * @returns StaticValue for use in static templates
 */
function unsafeStatic(value: string): StaticValue;

Usage Examples:

import { html, unsafeStatic } from 'lit-html/static.js';

// Dynamic static tag names (use with caution)
const createElementTemplate = (tagName: string) => {
  const tag = unsafeStatic(tagName);
  return html`<${tag}>Dynamic element</${tag}>`;
};

// Static attribute names from configuration
const createTemplate = (config: { idAttr: string }) => {
  const idAttr = unsafeStatic(config.idAttr);
  return html`<div ${idAttr}="value">Content</div>`;
};

Enhanced Template Functions

Template functions with static value support for optimized rendering.

Static HTML Template Function

Enhanced HTML template function that supports static values for optimization.

/**
 * Interprets a template literal as an HTML template that can efficiently
 * render to and update a container. Includes static value support.
 * @param strings - Template strings array
 * @param values - Template expression values (may include StaticValues)
 * @returns TemplateResult for rendering
 */
function html(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;

Usage Examples:

import { html, literal } from 'lit-html/static.js';

// Static element structure
const elementType = literal`article`;
const template = html`
  <${elementType} class="post">
    <h1>Title</h1>
    <p>Content goes here</p>
  </${elementType}>
`;

// Static attributes with dynamic values
const dataAttr = literal`data-post-id`;
const postTemplate = (id: number) => html`
  <article ${dataAttr}="${id}">
    <h1>Post ${id}</h1>
  </article>
`;

Static SVG Template Function

Enhanced SVG template function that supports static values for optimized vector graphics.

/**
 * Interprets a template literal as an SVG template that can efficiently
 * render to and update a container. Includes static value support.
 * @param strings - Template strings array
 * @param values - Template expression values (may include StaticValues)
 * @returns TemplateResult for rendering
 */
function svg(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;

Usage Examples:

import { html, svg, literal } from 'lit-html/static.js';

// Static SVG elements
const shapeType = literal`circle`;
const iconTemplate = (size: number) => html`
  <svg viewBox="0 0 100 100" width="${size}" height="${size}">
    ${svg`<${shapeType} cx="50" cy="50" r="40" fill="currentColor" />`}
  </svg>
`;

Static MathML Template Function

Enhanced MathML template function that supports static values for optimized mathematical notation.

/**
 * Interprets a template literal as MathML fragment that can efficiently
 * render to and update a container. Includes static value support.
 * @param strings - Template strings array
 * @param values - Template expression values (may include StaticValues)
 * @returns TemplateResult for rendering
 */
function mathml(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;

Static Template Wrapper

withStatic Function

Wraps any template tag function to add static value support.

/**
 * Wraps a lit-html template tag (html, svg, or mathml) to add static value support.
 * @param coreTag - The core template tag function to enhance
 * @returns Enhanced template tag function with static support
 */
function withStatic(
  coreTag: typeof coreHtml | typeof coreSvg | typeof coreMathml
): (strings: TemplateStringsArray, ...values: unknown[]) => TemplateResult;

Usage Examples:

import { html as coreHtml } from 'lit-html';
import { withStatic, literal } from 'lit-html/static.js';

// Create custom static-enabled template function
const customHtml = withStatic(coreHtml);

const tagName = literal`section`;
const template = customHtml`<${tagName}>Content</${tagName}>`;

Advanced Static Template Patterns

Component Templates with Static Structure

import { html, literal } from 'lit-html/static.js';

class MyComponent {
  static tagName = literal`my-component`;
  
  render(content: string) {
    const tag = MyComponent.tagName;
    return html`
      <${tag} class="component">
        <div class="content">${content}</div>
      </${tag}>
    `;
  }
}

Configuration-Driven Static Templates

import { html, unsafeStatic } from 'lit-html/static.js';

interface TemplateConfig {
  containerTag: string;
  titleTag: string;
  contentClass: string;
}

const createTemplate = (config: TemplateConfig) => {
  const container = unsafeStatic(config.containerTag);
  const title = unsafeStatic(config.titleTag);
  const contentClass = unsafeStatic(config.contentClass);
  
  return (titleText: string, content: string) => html`
    <${container}>
      <${title}>${titleText}</${title}>
      <div class="${contentClass}">${content}</div>
    </${container}>
  `;
};

// Usage
const articleTemplate = createTemplate({
  containerTag: 'article',
  titleTag: 'h1', 
  contentClass: 'article-content'
});

Static Attribute Names

import { html, literal } from 'lit-html/static.js';

// Define static attribute names for reuse
const dataIdAttr = literal`data-id`;
const ariaLabelAttr = literal`aria-label`;

const accessibleButton = (id: string, label: string, text: string) => html`
  <button ${dataIdAttr}="${id}" ${ariaLabelAttr}="${label}">
    ${text}
  </button>
`;

Performance Considerations

Static templates provide performance benefits by:

  1. Reduced Template Creation: Static parts are processed at compile time
  2. Smaller Runtime Size: Less dynamic template processing code
  3. Better Caching: Static templates can be more efficiently cached
  4. Compile-time Optimization: Tools can optimize static template structures
import { html, literal } from 'lit-html/static.js';

// This template structure is optimized at compile time
const optimizedTemplate = (data: any[]) => {
  const tableTag = literal`table`;
  const rowTag = literal`tr`;
  const cellTag = literal`td`;
  
  return html`
    <${tableTag} class="data-table">
      ${data.map(item => html`
        <${rowTag}>
          <${cellTag}>${item.name}</${cellTag}>
          <${cellTag}>${item.value}</${cellTag}>
        </${rowTag}>
      `)}
    </${tableTag}>
  `;
};

Types

interface StaticValue {
  /** The value to interpolate as-is into the template */
  _$litStatic$: string;
  /** Brand to prevent JSON injection attacks */
  r: typeof brand;
}

interface TemplateResult<T extends ResultType = ResultType> {
  readonly strings: TemplateStringsArray;
  readonly values: unknown[];
}

Import Patterns

// Static template functions (enhanced versions)
import { html, svg, mathml } from 'lit-html/static.js';

// Static value creation
import { literal, unsafeStatic } from 'lit-html/static.js';

// Template wrapper utility
import { withStatic } from 'lit-html/static.js';

// Core functions for wrapping
import { html as coreHtml } from 'lit-html';

// Example usage
const tagName = literal`div`;
const template = html`<${tagName}>Content</${tagName}>`;

Security Considerations

  • unsafeStatic: Only use with trusted content. Untrusted input can lead to XSS vulnerabilities
  • literal: Safe to use as it only accepts template literals from source code
  • Static values: Changes cause complete re-renders, so use for truly static content
  • Validation: Always validate dynamic input before passing to unsafeStatic

docs

built-in-directives.md

core-templates.md

custom-directives.md

index.md

static-templates.md

tile.json