Skip to content

Commit

Permalink
[fix] textContent should not be set for <template> element. (#7297)
Browse files Browse the repository at this point in the history
* [fix] textContent should not be set for <template> element.

* tidy - name convetion. minor refactor extract "is template" check to a variable and replace usages.

* test template with text content

* update html in test
  • Loading branch information
lidlanca committed Apr 16, 2022
1 parent df75dd7 commit fb341cc
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 12 deletions.
8 changes: 6 additions & 2 deletions src/compiler/compile/render_dom/wrappers/Element/index.ts
Expand Up @@ -420,8 +420,12 @@ export default class ElementWrapper extends Wrapper {
}

// insert static children with textContent or innerHTML
// skip textcontent for <template>. append nodes to TemplateElement.content instead
const can_use_textcontent = this.can_use_textcontent();
if (!this.node.namespace && (this.can_use_innerhtml || can_use_textcontent) && this.fragment.nodes.length > 0) {
const is_template = this.node.name === 'template';
const is_template_with_text_content = is_template && can_use_textcontent;

if (!is_template_with_text_content && !this.node.namespace && (this.can_use_innerhtml || can_use_textcontent) && this.fragment.nodes.length > 0) {
if (this.fragment.nodes.length === 1 && this.fragment.nodes[0].node.type === 'Text') {
block.chunks.create.push(
b`${node}.textContent = ${string_literal((this.fragment.nodes[0] as TextWrapper).data)};`
Expand Down Expand Up @@ -452,7 +456,7 @@ export default class ElementWrapper extends Wrapper {
this.fragment.nodes.forEach((child: Wrapper) => {
child.render(
block,
this.node.name === 'template' ? x`${node}.content` : node,
is_template ? x`${node}.content` : node,
nodes
);
});
Expand Down
24 changes: 16 additions & 8 deletions test/runtime/samples/template/_config.js
Expand Up @@ -2,22 +2,30 @@ export default {
// solo: 1,

html: `
<template>
<div>foo</div>
</template>
<template id="t1">
<div>foo</div>
</template>
<template id="t2">123</template>
`,

test({ assert, target }) {
const template = target.querySelector('template');


const template = target.querySelector('#t1');
assert.htmlEqual(template.innerHTML, `
<div>foo</div>
`);

<div>foo</div>
`);
const content = template.content.cloneNode(true);
const div = content.children[0];
assert.htmlEqual(div.outerHTML, `
<div>foo</div>
`);


const template2 = target.querySelector('#t2');
assert.equal(template2.childNodes.length, 0);
assert.equal(template2.content.childNodes.length, 1);
assert.equal(template2.content.firstChild.textContent, '123');
assert.htmlEqual(template2.innerHTML, '123');

}
};
5 changes: 3 additions & 2 deletions test/runtime/samples/template/main.svelte
@@ -1,3 +1,4 @@
<template>
<template id="t1">
<div>foo</div>
</template>
</template>
<template id="t2">123</template>

0 comments on commit fb341cc

Please sign in to comment.