Skip to content

Commit

Permalink
fix: serialize top-level template contents
Browse files Browse the repository at this point in the history
Before this, passing a `template` tag to `serialize` would result in an empty string.
  • Loading branch information
fb55 committed Feb 7, 2022
1 parent feaf509 commit a6f4b62
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
9 changes: 9 additions & 0 deletions packages/parse5/lib/serializer/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,13 @@ describe('serializer', () => {
assert.equal(html, '<div><button>Hello</button></div>');
});
});

it('serializes <template> elements inner content', () => {
const document = parse5.parseFragment('<template><button>Hello</button></template>');
const template = document.childNodes[0];
assert.ok(isElementNode(template));
const html = parse5.serialize(template);

assert.equal(html, '<button>Hello</button>');
});
});
17 changes: 9 additions & 8 deletions packages/parse5/lib/serializer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,14 @@ function serializeChildNodes<T extends TreeAdapterTypeMap>(
options: InternalOptions<T>
): string {
let html = '';
const childNodes = options.treeAdapter.getChildNodes(parentNode);
// Get container of the child nodes
const container =
options.treeAdapter.isElementNode(parentNode) &&
options.treeAdapter.getTagName(parentNode) === $.TEMPLATE &&
options.treeAdapter.getNamespaceURI(parentNode) === NS.HTML
? options.treeAdapter.getTemplateContent(parentNode)
: parentNode;
const childNodes = options.treeAdapter.getChildNodes(container);

if (childNodes) {
for (const currentNode of childNodes) {
Expand All @@ -139,13 +146,7 @@ function serializeElement<T extends TreeAdapterTypeMap>(node: T['element'], opti
return `<${tn}${serializeAttributes(node, options)}>${
options.treeAdapter.getNamespaceURI(node) === NS.HTML && VOID_ELEMENTS.has(tn)
? ''
: `${serializeChildNodes(
// Get container of the child nodes
tn === $.TEMPLATE && options.treeAdapter.getNamespaceURI(node) === NS.HTML
? options.treeAdapter.getTemplateContent(node)
: node,
options
)}</${tn}>`
: `${serializeChildNodes(node, options)}</${tn}>`
}`;
}

Expand Down

0 comments on commit a6f4b62

Please sign in to comment.