Skip to content

Commit

Permalink
Merge pull request #1073 from sveltejs/gh-1066
Browse files Browse the repository at this point in the history
Escape entities correctly when compiling to static HTML
  • Loading branch information
Rich-Harris authored Jan 5, 2018
2 parents 70ce51d + 7026222 commit 521fd74
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/generators/nodes/Element.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import deindent from '../../utils/deindent';
import { stringify } from '../../utils/stringify';
import { stringify, escapeHTML } from '../../utils/stringify';
import flattenReference from '../../utils/flattenReference';
import isVoidElementName from '../../utils/isVoidElementName';
import validCalleeObjects from '../../utils/validCalleeObjects';
Expand Down Expand Up @@ -414,7 +414,7 @@ export default class Element extends Node {
}

function toHTML(node: Element | Text) {
if (node.type === 'Text') return node.data;
if (node.type === 'Text') return escapeHTML(node.data);

let open = `<${node.name}`;

Expand Down
4 changes: 2 additions & 2 deletions src/generators/server-side-rendering/visitors/Text.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { SsrGenerator } from '../index';
import Block from '../Block';
import { escape } from '../../../utils/stringify';
import { escape, escapeHTML } from '../../../utils/stringify';
import { Node } from '../../../interfaces';

export default function visitText(
generator: SsrGenerator,
block: Block,
node: Node
) {
generator.append(escape(node.data).replace(/(\${|`|\\)/g, '\\$1'));
generator.append(escapeHTML(escape(node.data).replace(/(\${|`|\\)/g, '\\$1')));
}
12 changes: 12 additions & 0 deletions src/utils/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,15 @@ export function escape(data: string, { onlyEscapeAtSymbol = false } = {}) {
return match + match[0];
});
}

const escaped = {
'"': '&quot;',
"'": '&##39;',
'&': '&amp;',
'<': '&lt;',
'>': '&gt;'
};

export function escapeHTML(html) {
return String(html).replace(/["'&<>]/g, match => escaped[match]);
}
5 changes: 5 additions & 0 deletions test/runtime/samples/html-entities-inside-elements/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
html: `
<p>this &lt;em&gt;should&lt;/em&gt; not be <span>&lt;strong&gt;bold&lt;/strong&gt;</span></p>
`
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>this &lt;em&gt;should&lt;/em&gt; not be <span>&lt;strong&gt;bold&lt;/strong&gt;</span></p>
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<div>
<p>foo: ''</p>
<p>foo: &#39;&#39;</p>
</div>

0 comments on commit 521fd74

Please sign in to comment.