我正在从数据库表中获取模板,值返回为
Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}
这些值在请求有效载荷中
这就是我尝试动态使用模板文字的方式。
const arg = { customerName: "Ram", websiteLink: "https://www.google.com"}
const template = getMessageTemplateFromDb('customer');
const messageContent = getMessageContent(args, template);
const getMesageContent = (args, template) => {
const { customerName, websiteLink} = args;
return `${template}`;
};
我期待
getMesageContent
返回值 as
Hello Ram: Welcome! to our site. This is dummy.Please reach us at https://www.google.com
但事实并非如此,我得到的值是
Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}
如何在运行时设置模板和参数?
请注意,我在这里看到了一些方法 https://stackoverflow.com/a/22619256/1326367,但是 EsLint 对这些大喊大叫。
谢谢!
如果您更改链接帖子的正则表达式,则可以使用该技术。
const arg = { customerName: "Ram", websiteLink: "https://www.google.com"},
raw = 'Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}',
get = (args, template) => template.replace(/\$\{(.*?)\}/g, (match, id) => args[id]);
const replaced = get(arg, raw);
console.log(replaced)
// Hello Ram: Welcome! to our site. This is dummy.Please reach us at https://www.google.com