模板部件
这个库被设计成一个"poyfill"的库,在其中执行设计 Template Instance 提议什么wg spec 已提议解决 什么wg/html#2254。 。 。 .
这样做可以执行提案中最低可行部分,以便提供行之有效的东西,但如果模板部分提案落地,就应容易减少.
重申上述提案中的例子,并提供一个模板,例如:
<template id="foo">
<div class="foo {{y}}">{{x}} world</div>
</template>
我们想 {{x}} 财务报告和审定财务报表 {{y}} 将会是 模板部件,作为 JavaScript 可被操纵的对象曝光.
有了这个库和给定的模板,就可以执行以下内容:
import {TemplateInstance} from '@github/template-parts'
const tpl = new TemplateInstance(document.getElementById('some-template'), { x: 'Hello', y: 'bar'})
document.appendChild(tpl)
A 类 TemplateInstance 实例是 DocumentFragment - 包含模板的克隆内容。 也有一个 update(params: unknown): void 方法 - 当调用时将运行给定的“ 处理器”, 并使用新的 params。 。 。 .
这个库有一个默认的"处理器": propertyIdentity 执行将参数对象值应用到模板部件的基本功能(它有效) part.value = params[part.expression](中文(简体) )
此外,还有一个 propertyIdentityOrBooleanAttribute 导出可增加转动能力 boolean 样式属性如 hidden 或者说 input.required。 。 。 .
用来使用 propertyIdentityOrBooleanAttribute,将其导入并传递给 TemplateInstance 构造器 :
import {TemplateInstance, propertyIdentityOrBooleanAttribute} from '@github/template-parts'
// This will simply replace `{{x}}` with `"Hello"` and `{{y}}` with `"bar"`
const tpl = new TemplateInstance(document.getElementById('foo'), { x: 'Hello', y: 'bar'})
// The `propertyIdentityOrBooleanAttribute` processor will check for `false`/`true` values which map to Template Part values that are assigned to attributes, and add/remove the attribute.
const tpl = new TemplateInstance(document.getElementById('foo'), { x: 'Hello', hidden: false}, propertyIdentityOrBooleanAttribute)