[英]Vue3 composition API template replacement without eval
So, I'm building a system that allows users to create document templates.因此,我正在构建一个允许用户创建文档模板的系统。 I have a pretty simple, human readable way of adding "dynamic" data to the templates:
我有一种非常简单、人类可读的方式将“动态”数据添加到模板中:
#firstName from client#" <--- where "client" is a ref(), and firstName would be a property of that object. #firstName from client#" <--- 其中“client”是 ref(),firstName 是该对象的属性。
Now, I can figure out how to replace these tags with the actual data without using eval().现在,我可以弄清楚如何在不使用 eval() 的情况下用实际数据替换这些标签。 Now, obviously I can't trust what people enter here, so I have an array of "allowedTags", and when I parse, I only parse the RegEx matched list of #..# values.
现在,显然我不能相信人们在这里输入的内容,所以我有一个“allowedTags”数组,当我解析时,我只解析 #..# 值的 RegEx 匹配列表。 So they can't do anything like #someEvil code here from SomeOtherEvilStuff" because it won't be an allowed tag.
因此,他们不能在此处从 SomeOtherEvilStuff 执行类似 #someEvil 代码之类的操作,因为它不是允许的标签。
Is this really that bad, or is there another way to dynamically replace using ref() values?这真的那么糟糕,还是有另一种方法可以使用 ref() 值动态替换?
function processTemplate(text: string): string {
const re = new RegExp(/#\w+ from \w+#/, 'g')
const matches = text.match(re) ?? []
for (const match of matches) {
if (!allowedTemplateTags.includes(match)) {
continue
}
const split = match.replace(/#/g, '').split(' from ')
const replaceRegEx = new RegExp(`(${match})`, 'g')
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
text = text.replace(replaceRegEx, eval(`${split[1]}?.value.${split[0]}`))
}
return text
}
So basically what you want is access variables of which you get the name from the user?所以基本上你想要的是你从用户那里得到名字的访问变量? My approach would be to have a reactive data object and just use the strings to point at the correct entry.
我的方法是拥有一个反应数据对象,并使用字符串指向正确的条目。
import { reactive } from ‘vue’;
// For the idea: these two strings you get from the user
const string1 = ‘firstName’;
const string2 = ‘client’;
const data = reactive({
client: {
firstName: ‘John’,
});
const text = data[string2][string1] // text will be ‘John’
data[string2][string1] = ‘Anna’; // now firstName will be ‘Anna’
I did not test this code, but I think you get the idea.我没有测试这段代码,但我想你明白了。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.