@github/jtml

中文文档
0.5.1发布于 2023/05/10MITES Module近 30 天下载 4722

Write HTML in JavaScript, using template-tags

原始使用文档
文档目录7 节
  1. @github/jtml
  2. Basic Usage
  3. Expressions
  4. Directives
  5. Built in Directives
  6. until
  7. CSP Trusted Types

@github/jtml

This library is designed as a layer on top of @github/template-parts to provide declarative, JavaScript based HTML template tags.

This library is heavily inspired by lit-html, which GitHub has used in production for a while. This was created independently from lit-html for the following reasons:

Basic Usage

This library comes with a set of exports, the main two being html and render.

html is a "tagged template" function. Rather than calling it, you "tag" a template string with html and it will return a TemplateResult which can be used to render HTML safely, on the client side.

import {html, render} from '@github/jtml'

const greeting = 'Hello'
render(html`<h1>${greeting} World</h1>`, document.body)

The benefit of this over, say, setting innerHTML is that the tagged template can be re-used efficiently, causing less mutations in the DOM:

import {html, render} from '@github/jtml'

const theTime = date => html`<p>The time is ${date.toString()}</p>`
setInterval(() => render(theTime(new Date()), document.body), 1000)

Expressions

jtml interpolates placeholder expressions in special ways across the template. Depending on where you put a placeholder expression (the ${} syntax is a placeholder expression) depends on what it does. Importantly "Attributes" behave differently to "Nodes". Here is a comprehensive list:

Attributes

HTML Attributes can contain placeholder expressions, but these must be inside the quoted part of the attribute. The name of an Attribute cannot use placeholder expressions, only the value.

import {html, render} from '@github/jtml'

const className = `red-box`

html`<p class="${className}"></p>` // This is valid

html`<p class=${className}></p>` // !! This is INVALID!
html`<p ${attr}="test"></p>` // !! This is INVALID!
Boolean Values

If an attribute maps to a "boolean attribute", and the attribute value consists solely of a placeholder expression which evaluates to a boolean, then this can be used to toggle the attribute on or off. For example:

import {html, render} from '@github/jtml'

const input = (required = false) => html`<input required="${required}" />`
const div = (hidden = false) => html`<div hidden="${hidden}"></div>`

render(input(false), document.body) // Will render `<input />`
render(input(true), document.body) // Will render `<input required />`

render(div(true), document.body) // Will render `<div></div>`
render(div(false), document.body) // Will render `<div></div>`
Multiple values, whitespace

If an attribute consists of multiple placeholder expressions, these will all be mapped to strings. Any included whitespace is also rendered as you might expect. Here's an example:

import {html, render} from '@github/jtml'

const p = ({classOne, classTwo, classThree}) => html`<p class="${classOne} ${classTwo} ${classThree}"></p>`

render(p({classOne: 'red', classTwo: 'box', classThree: ''}), document.body)
// ^ Renders `<p class="red box  "></p>`

const i = ({classOne, classTwo}) => html`<i class="${classOne}-${classTwo}"></i>`

render(i({classOne: 'red', classTwo: 'box'}), document.body)
// ^ Renders `<i class="red-box"></i>`
Iterables (like Arrays)

Any placeholder expression which evaluates to an Array/Iterable is joined with spaces (Array.from(value).join(' ')). This means you can pass in an Array of strings and it'll be rendered as a space separated list. These can still be mixed with other placeholder expressions or static values. An example:

import {html, render} from '@github/jtml'

const p = ({classes, hidden = false}) => html`<p class="bold ${classes} ${hidden ? 'd-none' : ''}"></p>

render(p({classes: ['red', 'box'], hidden: true}), document.body)
// ^ Renders `<p class="bold red box d-none"></p>`

render(p({classes: ['red', 'box'], hidden: false}), document.body)
// ^ Renders `<p class="bold red box "></p>`
Events

If an attributes name begins with on, and the value consists of a single placeholder expression that evaluates to a function, then this will become an Event Listener, where the event name is the attribute name without the on, so for example:

import {html, render} from '@github/jtml'

const handleClick = e => console.log('User clicked!')

render(html`<button onclick="${handleClick}"></button>`, document.body)
// ^ Renders `<button></button>`
// Effectively calls `button.addEventListener('click', handleClick)`

The event name can be any event name that is also possible as an attribute, for example onloaded will listen for the loaded event, onwill-load will bind to the will-load event. Special characters such as :s are not allowed as attribute names, and as such you cannot bind to an event name with these special characters using this pattern.

Nodes

Placeholder expressions can also be put where an HTML node might be - in other words inside a tag, rather than inside an attribute. These behave differently to placeholder expressions inside attribute values:

HTML Escaping

Any HTML inside a string is automatically escaped. Values get added as Text nodes, meaning it is impossible to inject HTML unless you explicitly want to, making them safe for XSS. This is not manually handled by the library, but is core to the design - meaning the browser handles this escaping! An example:

import {html, render} from '@github/jtml'

const unsafe = '<script>alert(1)</script>'

render(html`<div>${unsafe}</div>`, document.body)
// ^ Renders `<div>&lt;script&gt;alert(1)&lt;/script&gt;</div>`
Sub Templates

If a placeholder expression evaluates to a sub template, then that sub template will be rendered and added to as a child to the node, in the position you'd expect:

import {html, render} from '@github/jtml'

const embolden = word => html`<strong>${word}</strong>`

render(html`<div>Hello ${embolden('world')}!</div>`, document.body)
// ^ Renders `<div>Hello <strong>world</strong>!</div>`

Document Fragments

You can also pass document fragments in, and they will be rendered as you might expect. This is useful for mixing-and-matching template libraries:

import {html, render} from '@github/jtml'

const vanillaEmbolden = word => {
  const frag = document.createDocumentFragment()
  const strong = document.createElement('strong')
  strong.append(String(word))
  frag.append(strong)
  return frag
}

render(html`<div>Hello ${vanillaEmbolden('world')}!</div>`, document.body)
// ^ Renders `<div>Hello <strong>world</strong>!</div>`
Iterables (like Arrays)

Any placeholder expression which evaluates to an Array/Iterable is evaluated per-item. If a single item is a Document Fragment or Sub Template then it will be rendered as you might expect, otherwise it is treated as a String and gets added as a Text node. All of the contents of the Array will be rendered as one. Some examples:

import {html, render} from '@github/jtml'

const data = [ { name: 'Spanner', value: 5 }, { name: 'Wrench', value: 5 } ]

const row = ({name, value}) => html`<tr><td>${name}</td><td>${value}</td></td>`
const table = rows => html`<table>${rows.map(row)}</table>`

render(table(data), document.body)
// ^ Renders 
// <table>
//   <tr><td>Spanner</td><td>5</td></tr>
//   <tr><td>Wrench</td><td>5</td></tr>
// </table>

Directives

For more advanced behaviours, a function can be wrapped with the directive function to create a Directive which gets to customize the rendering flow. jtml also includes some built in directives (see below).

A directive must follow the following signature. It can take any number of arguments (which are ignored) and must return a function which receives the TemplatePart:

type Directive = (...values: unknown[]) => (part: TemplatePart) => void

Here's an example of how a directive might work:

import {html, render, directive} from '@github/jtml'

// A directive can take any number of arguments, and must return a function that takes a `TemplatePart`.
const renderLater = directive((text, ms) => part => {
  // A parts value can be set using `.value`
  part.value = 'Loading...'
  setTimeout(() => part.value = text, ms)
})

render(html`<div>${renderLater('Hello world', 1000)}`, document.body)
// ^ Renders <div>Loading...</div>
// After 1000ms, changes to `<div>Hello world</div>`

Built in Directives

until

jtml ships with a built-in directive for handling Promise values, called until. until takes any number of Promises, and will render them, right to left, as they resolve. This is useful for passing in asynchronous values as the first arguments, timeout messages as the middle value, and synchronous values for the placeholder values, like so:

import {html, render, until} from '@github/jtml'

const delay = (ms, value) => new Promise(resolve => setTimeout(resolve, ms, value))

const request = delay(1000, 'Hello World')
const loading = 'Loading...'
const timeout = delay(2000, 'Failed to load')

render(html`<div>${until(request, timeout, loading)}</div>`)
// ^ renders <div>Loading...</div>
// After 1000ms will render <div>Hello World</div>
import {html, render, until} from '@github/jtml'

const delay = (ms, value) => new Promise(resolve => setTimeout(resolve, ms, value))

const request = delay(3000, 'Hello World') // Request takes longer than the timeout
const loading = 'Loading...'
const timeout = delay(2000, 'Failed to load')

render(html`<div>${until(request, timeout, loading)}</div>`)
// ^ renders <div>Loading...</div>
// After 2000ms will render <div>Failed to load</div>

CSP Trusted Types

You can call TemplateResult.setCSPTrustedTypesPolicy(policy: TrustedTypePolicy | Promise<TrustedTypePolicy> | null) from JavaScript to set a CSP trusted types policy, which can perform (synchronous) filtering or rejection of the rendered template:

import {TemplateResult} from "@github/jtml";
import DOMPurify from "dompurify"; // Using https://github.com/cure53/DOMPurify

// This policy removes all HTML markup except links.
const policy = trustedTypes.createPolicy("links-only", {
  createHTML: (htmlText: string) => {
    return DOMPurify.sanitize(htmlText, {
      ALLOWED_TAGS: ["a"],
      ALLOWED_ATTR: ["href"],
      RETURN_TRUSTED_TYPE: true,
    });
  },
});
TemplateResult.setCSPTrustedTypesPolicy(policy);

Note that:

  • Only a single policy can be set, shared by all render and unsafeHTML calls.
  • You should call TemplateResult.setCSPTrustedTypesPolicy() ahead of any other call of @github/jtml in your code.
  • Not all browsers support the trusted types API in JavaScript. You may want to use the recommended tinyfill to construct a policy without causing issues in other browsers.

版本与发布记录

@github/jtml 共发布 13 个版本,首次发布于 2020/10/27;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.5.1latest2023/05/103 年前
0.5.02022/12/133 年前
0.4.12022/01/264 年前
0.4.02021/03/095 年前
0.3.42021/03/015 年前
0.3.32021/01/265 年前

关于 @github/jtml 的常见问题

@github/jtml 是什么?

Write HTML in JavaScript, using template-tags

如何安装 @github/jtml?

在项目目录运行 npm install @github/jtml,或使用 pnpm add / yarn add / bun add。

@github/jtml 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/github__jtml 是否存在。

@github/jtml 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@github/jtml 可以商用吗?

@github/jtml 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@github/jtml 的下载量有多少?

根据 npm 官方下载统计,@github/jtml 在 2026/10/17 – 2026/11/15 这 30 天内被下载 4,722 次,日均约 157 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@github/jtml 还在维护吗?

最新版本 0.5.1 发布于 2023/05/10(3 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/10/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。