示例
您可以创建一个HTML`...`模板字符串标记函数来自动编码内插值。(这要求将插值仅用作文本,并且如果在脚本或样式等代码中使用插值,则可能不安全。)
class HTMLString extends String {
static escape(text) {
if (text instanceof HTMLString) {
return text;
}
return new HTMLString(
String(text)
.replace(/&/g, '&')
.replace(/
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/\\/g, '''));
}
}
function HTML(strings, ...substitutions) {
const escapedFlattenedSubstitutions =
substitutions.map(s => [].concat(s).map(HTMLString.escape).join(''));
const pieces = [];
for (const i of strings.keys()) {
pieces.push(strings[i], escapedFlattenedSubstitutions [i] || '');
}
return new HTMLString(pieces.join(''));
}
const title = "Hello World";
const iconSrc = "/images/logo.png";
const names = ["John", "Jane", "Joe", "Jill"];
document.body.innerHTML = HTML`
${title}
- ${names.map(name => HTML`
- ${name}
`)}
`;