我有一些JSON,看起来有点像这样:
component.json
[
{ "template": "<div class="${layout} ${border}"></div>" },
{
"layout": "grid",
"border": "primary"
}
]
我正在使用这个JSON通过JS生成一些HTML,我不知道如何将";布局";以及";"边界";转换为变量,然后可以将这些变量添加到模板字符串中。
对于上下文,我不能只对变量进行硬编码,在JSON中,我无法预测会有多少变量或它们是什么。
我正在尝试这样的东西:
const template = componentJSON[0].template
const classes = componentJSON[1]
for (const [key, value] of Object.entries(classes)) {
eval('var ' + `${key}` + ' = ' + '"' + `${value}` + '"')
}
let html = eval('`' + template + '`')
我知道EVIL是eval,所以我很高兴听到其他解决方案,但也很高兴听到eval的选项,因为它永远不会受到攻击。
我不知道为什么应该使用eval创建变量的for循环不起作用?也许eval是专门为不创建变量而构建的?我可以用new Function((代替吗?
作为参考,我希望的结果应该是:
<div class="grid primary"></div>
没有必要为此使用eval()
。将replace()
方法与匹配${...}
并替换为相应对象属性的regexp一起使用。
let componentJSON = [
{ "template": "<div class='${layout} ${border}'></div>" },
{
"layout": "grid",
"border": "primary"
}
];
const template = componentJSON[0].template
const classes = componentJSON[1]
let html = template.replace(/${(.*?)}/g, (match, key) => classes[key]);
console.log(html);