1

I have HTML e-mail templates stored in a MySQL database. Most of them include JavaScript variables. I tried to store them using template literals (i.e.: ${this.auth.user.name}) but this will not return the variable but the exact string. I assume my problem is because the string is encapsulated by double quotes or single quotes and not back-ticks.

So my JavaScript looks the following, where template is an array of objects queried from my MySQL show here.

var email_template: this.template[0].body;

The actual output is Hello ${this.auth.name}!

I expect the output of Hello Jack!

Do you have any ideas what could be the problem?

Thanks in advance, Tibor

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
user3599604
  • 31
  • 10
  • If you're pulling something from a DB, it isn't a template literal. Please do not use `new Function` or `eval` or else you're opening up a massive security hole in your application, unless you parse and validate the template fully first. – loganfsmyth May 29 '19 at 16:20

1 Answers1

2

Try making a new Function like so:

const name = "Jack";
const string = "Hello ${name}";
const actualString = new Function("return `" + string + "`").call(string);
console.log(actualString);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79