简体   繁体   English

用户定义的模板字符串

[英]User-defined template string

I'm looking for a way to give a user an option to define template literal.我正在寻找一种方法来为用户提供定义模板文字的选项。 That template will be sent to backend and used with the data he provided.该模板将被发送到后端并与他提供的数据一起使用。

Example scenario:示例场景:

const dataSentToBackend = [
  {
    name: 'Adam',
    country: 'Spain'
  },{
    name: 'Eve',
    country: 'Germany'
  }
]

User wants to generate two files that are like that: {name} from {country} (or anything else that let's him use tags how he like).用户想要生成两个类似的文件: {name} from {country} (或其他任何让他使用他喜欢的标签的东西)。 So files in this example would be named as Adam from Spain and Eve from Germany .因此,此示例中的文件将命名为Adam from SpainEve from Germany

The trick is that template needs to be preserved as a template so it can be used when data is actually being processed at the backend.诀窍是模板需要保留为模板,以便在后端实际处理数据时可以使用它。 So it can be used in a loop that names files one by one by the dataSentToBackend array.因此,它可以用于通过dataSentToBackend数组一一命名文件的循环中。

So far I only found String.raw function (thanks to this page), but I didn't found it much helpful for me (or I didn't understood it).到目前为止,我只找到了String.raw函数(感谢 这个页面),但我没有发现它对我有多大帮助(或者我没有理解它)。

Here's one way of doing it.这是一种方法。 I used the regular expression [az]+ for the property name which you could expand if you need to allow more characters (uppercase, underscores, numbers etc.)我使用正则表达式[az]+作为属性名称,如果您需要允许更多字符(大写、下划线、数字等)

 const dataSentToBackend = [ { name: 'Adam', country: 'Spain' }, { name: 'Eve', country: 'Germany' } ] const templateSentToBackend = "{name} from {country}"; serverSideReplace = (template, datas) => datas.map(data => template.replace(/\\{([az]+)\\}/g, (_, key) => data[key])); console.log(serverSideReplace(templateSentToBackend, dataSentToBackend));

Assuming that your user is inputing is template string in an input field.假设您的用户在输入字段中输入的是模板字符串。 You can simple save an escaped string in your database, and unescape the same before compiling it into template string.您可以简单地将转义的字符串保存在数据库中,并在将其编译为模板字符串之前将其取消转义。

And to actually use it back you can try something like this.要实际使用它,您可以尝试这样的操作。

const templateString = "Hello ${this.name}!"; // replace it with unescaped template 
const templateVars = {
    name: "world"    
}

const fillTemplate = function(templateString, templateVars){
    return new Function("return `"+templateString +"`;").call(templateVars);
}

console.log(fillTemplate(templateString, templateVars));

But i would definitely say don't let user define templates and use it, unless you have a really solid sanitizing script.但我肯定地说,不要让用户定义的模板和使用它,除非你有一个非常坚实的消毒脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM