-1

I'm fetching template from the db table & the value is returned as

Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}

The values of these are in the req payload

This is how I tried to use the template literals dynamically.

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}`;
};

I was expecting getMesageContent to return the value as

Hello Ram: Welcome! to our site. This is dummy.Please reach us at https://www.google.com

but that's not the case, I get the value as

Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}

How can I set the template & args at runtime?

Please note, I see some ways to do here https://stackoverflow.com/a/22619256/1326367, however EsLint yells at these.

Thanks!

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • 1
    _"however EsLint yells at these."_ - and ...? You want to use _data_ to perform functionality that you only get in a _code_ setting here, so you will either need to use some workarounds like that; or write your own parser. – CBroe Feb 28 '23 at 11:04

1 Answers1

1

If you change the Regex of your linked post, you can use that technique.

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
0stone0
  • 34,288
  • 4
  • 39
  • 64