template-parts

Compact template-parts ponyfill

Usage no npm install needed!

<script type="module">
  import templateParts from 'https://cdn.skypack.dev/template-parts';
</script>

README

template-parts test npm version

Compact template parts ponyfill.

Difference from @github/template-parts:

  • InnerTemplatePart support.
  • Improved parser (#38, #44).
  • More complete spec API surface.
  • <table><!--{{ data }}--></table> support* (#24).
  • Single vanilla ESM, no tooling.

Usage

import { TemplateInstance } from 'template-parts'

let tpl = new TemplateInstance(templateElement, initParams, processor)
tpl.update(newParams)
Spec surface
interface TemplateInstance : DocumentFragment {
    void update(any state);
};

callback TemplateProcessCallback = void (TemplateInstance, sequence<TemplatePart>, any state);

dictionary TemplateProcessor {
    TemplateProcessCallback processCallback;
    TemplateProcessCallback? createCallback;
};

interface TemplatePart {
    readonly attribute DOMString expression;
    attribute DOMString? value;
};

interface AttributeTemplatePart : TemplatePart {
    readonly attribute Element element;
    readonly attribute DOMString attributeName;
    readonly attribute DOMString attributeNamespace;
    attribute boolean booleanValue;
};

interface NodeTemplatePart : TemplatePart {
    readonly attribute ContainerNode parentNode;
    readonly attribute Node? previousSibling;
    readonly attribute Node? nextSibling;
    [NewObject] readonly NodeList replacementNodes;
    void replace((Node or DOMString)... nodes);
    void replaceHTML(DOMString html);
};

interface InnerTemplatePart : NodeTemplatePart {
    HTMLTemplateElement template;
    attribute DOMString directive;
};

Tables

Due to HTML quirk in table parsing, table fields should be wrapped into comment:

<table>
  <!--{{ thead }}-->
  <tbody>
    <!--{{ rows }}-->
  </tbody>
</table>

InnerTemplatePart

Templize recognizes inner templates as InnerTemplatePart, expecting directive and expression attributes.

<template>
  <div>
    <template directive="x" expression="x">{{x}}</template>
  </div>
</template>

See also

  • templize − elaborate expressions and reactive props processor for template-parts.

Alternatives

🕉