Skip to content

Commit 5c3e242

Browse files
authored
Merge pull request #65 from seanpdoyle/node-template-part
Extend `processPropertyIdentity` to handle Element
2 parents 001646f + f6ab0f3 commit 5c3e242

File tree

4 files changed

+16
-3
lines changed

4 files changed

+16
-3
lines changed

src/processors.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export function createProcessor(processPart: PartProcessor): TemplateTypeInit {
1919
}
2020

2121
export function processPropertyIdentity(part: TemplatePart, value: unknown): void {
22-
part.value = String(value)
22+
part.value = value instanceof Element ? value : String(value)
2323
}
2424

2525
export function processBooleanAttribute(part: TemplatePart, value: unknown): boolean {

src/template-instance.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {propertyIdentity} from './processors.js'
55
import {TemplatePart, TemplateTypeInit} from './types.js'
66

77
function* collectParts(el: DocumentFragment): Generator<TemplatePart> {
8-
const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null, false)
8+
const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null)
99
let node
1010
while ((node = walker.nextNode())) {
1111
if (node instanceof Element && node.hasAttributes()) {

src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type {TemplateInstance} from './template-instance.js'
22

33
export interface TemplatePart {
44
expression: string
5-
value: string | null
5+
value: Element | string | null
66
}
77

88
type TemplateProcessCallback = (instance: TemplateInstance, parts: Iterable<TemplatePart>, params: unknown) => void

test/template-instance.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,19 @@ describe('template-instance', () => {
1414
root.appendChild(instance)
1515
expect(root.innerHTML).to.equal(`Hello world`)
1616
})
17+
it('applies data to templated element nodes', () => {
18+
const template = document.createElement('template')
19+
const element = Object.assign(document.createElement('div'), {
20+
innerHTML: 'Hello world'
21+
})
22+
const originalHTML = `{{x}}`
23+
template.innerHTML = originalHTML
24+
const instance = new TemplateInstance(template, {x: element})
25+
expect(template.innerHTML).to.equal(originalHTML)
26+
const root = document.createElement('div')
27+
root.appendChild(instance)
28+
expect(root.innerHTML).to.equal(`<div>Hello world</div>`)
29+
})
1730
it('can render into partial text nodes', () => {
1831
const template = document.createElement('template')
1932
const originalHTML = `Hello {{x}}!`

0 commit comments

Comments
 (0)