0

I'm trying to create an object with string templates in it. How do I do that? If I use double quotes for the message -- see below -- I'm not getting a template. If I use back-ticks, I'm getting an error.

const templates = {
   "hello": {message: `Hello ${name}!`},
   "price": {message: `How much is this ${product}?`}
}

The idea is to return a custom message that looks something like this. The code below is not complete but you'll get the idea.

const getMessage = (type, name, product) => {
   const message = templates[type].message;
   return message;
}
Sam
  • 26,817
  • 58
  • 206
  • 383
  • Your first code already works. – Oriol Dec 20 '16 at 18:24
  • The suspense is killing me... what's the error!? – Heretic Monkey Dec 20 '16 at 18:24
  • @Gothodo : it is not duplicated – Abdennour TOUMI Dec 20 '16 at 18:27
  • The error is Uncaught ReferenceError: name is not defined. This is in the templates object. – Sam Dec 20 '16 at 18:28
  • Do I need to pass name, product to the templates object for it to work? How would I even do that? – Sam Dec 20 '16 at 18:29
  • 2
    @AbdennourTOUMI You're going to have to be more specific about why it's not a duplicate. – 4castle Dec 20 '16 at 18:31
  • See also http://stackoverflow.com/questions/41071779/template-literal-trapped-in-a-string-variable/41073463#41073463 and http://stackoverflow.com/questions/34882100/can-you-dumb-down-es6-template-strings-to-normal-strings/34883543#34883543. –  Dec 20 '16 at 18:35
  • Fundamentally the easiest fix would be to make your template object contain functions that accept the variables and return a string. As it is now, the template is resolved into a string at the moment the templates object is created, at which point none of that context exists. – PMV Dec 20 '16 at 20:34

0 Answers0