使用模板字串模板化 HTML
你可以建立HTML`...`
模板字串標記函式以自動編碼插值。 (這要求插值僅用作文字,如果在指令碼或樣式等程式碼中使用插值,則可能不安全。)
class HTMLString extends String {
static escape(text) {
if (text instanceof HTMLString) {
return text;
}
return new HTMLString(
String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.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`
<h1><img src="${iconSrc}" /> ${title}</h1>
<ul> ${names.map(name => HTML`
<li>${name}</li>
`)} </ul>
`;