我构建了一个网络应用程序,它与许多屏幕相结合,我每次都想加载其中的一部分。所以我使用数据对象和 html 标记。但由于我加载了许多模板,我希望将 html 数据解析为小的 html 文件,当 web 应用程序需要它们时将读取它们。
const customer = {
name: 'john doe',
title: 'Web Developer',
city: 'NY'
}
const markup = `
<div class="customer">
<h2>
${customer.name}
</h2>
<p class="location">${customer.location}</p>
<p class="title">${customer.title}</p>
</div>
`;
我真正想要的是标记 html 将从外部文件中获取
所以我尝试通过调用ajax并将html保存为变量来获取模板字符串,但似乎没有解析模板文字
任何帮助将不胜感激
最佳答案
嗯,HTML 中没有内置的数据绑定(bind),而这些功能是由 Angular 等框架提供的。但是,如果你想保持原样,你可以选择这样的东西:
const customer = {
name: 'john doe',
title: 'Web Developer',
city: 'NY'
}
const markupFromExternalFile = `
<div class="customer">
<h2>
{customer.name}
</h2>
<p class="location">{customer.city}</p>
<p class="title">{customer.title}</p>
</div>
`
const regex = /\{(.*?)\}/g
let finalMarkup = markupFromExternalFile
const changes = finalMarkup.matchAll(regex)
while(true) {
const change = changes.next()
if(change.done) break
const [replacement, prop] = change.value
finalMarkup = finalMarkup.replace(replacement, customer[prop.split('.').pop()])
}
console.log(finalMarkup)
在这里,请确保 HTML 标记中的属性名称与从中获取该属性的对象的属性名称相匹配。
关于javascript - 如何将 es6 模板文字与外部 html 文件一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101360/