0

Im trying to use a template literal on a value coming from the database, this values is saved like below

{
"classical" : "cs",
"state" : "myState",
"template" : "this is ${countryName} <b>Thanks for ${departmentName}</>"
}

this is how it is saved in my database. Now during my business logic i read this record and get the template value and save it to a variable. I want to replace {countryName} and with some value coming from data.

I have tried using the render function of Email template module but it doesnt work. Below are some code that i have tried.

Method 1:

 function render(template, dataNext) {
             return template(dataNext);
     }
    const tpl = () => `${myDBObject[0].template}`;
    console.log(render(tpl, { countryName: "India", departmentName: "science"}));

Above i have hardcoded India just for understanding purpose and that value will also come from database.

Im expecting some es6 ways to replace these containers with my values.

The JOKER
  • 453
  • 8
  • 21
  • Do you know what will be the name of the variables in the template (in your example `countryName` and `departmentName`)? If so, a simple `.replace` can do the job – AbM Oct 10 '19 at 06:46
  • 1
    Possible duplicate of [Convert a string to a template string](https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string) – mbojko Oct 10 '19 at 06:58
  • where is countryName and departmentName coming from ?? – vipul patel Oct 10 '19 at 07:08

2 Answers2

0

Below is a example of how to use template literals. Modify it according to what you need. Read more on template literals

const countryName = 'United Kingdom';
const departmentName = 'IT';
const obj = {
  "classical": "cs",
  "state": "myState",
  "template": `This is <b> ${countryName}</b> <br/> Thanks for ${departmentName}`
}

document.getElementById('template').innerHTML = obj.template;
console.log(obj.template);
<div id="template"></div>

but for you this might not work as its stored as a string in your database so for your case you can either use replace method to replace the values. Like below.

const countryName = 'United Kingdom';
const departmentName = 'IT';
const obj = {
  "classical": "cs",
  "state": "myState",
  "template": "This is <b> ${countryName}</b> <br/> Thanks for ${departmentName}"
}

obj.template = obj.template.replace('${countryName}', countryName);
obj.template = obj.template.replace('${departmentName}', departmentName);
document.getElementById('template').innerHTML = obj.template;
console.log(obj.template);
<div id="template"></div>

Or you can even make use of eval (though not recommended) to convert it into a template literal.

const countryName = 'United Kingdom';
const departmentName = 'IT';
const obj = {
  "classical": "cs",
  "state": "myState",
  "template": "This is <b> ${countryName}</b> <br/> Thanks for ${departmentName}"
}

obj.template = eval('`' + obj.template + '`');
document.getElementById('template').innerHTML = obj.template;
console.log(obj.template);
<div id="template"></div>

Recommendation:

The best possible solution in your case is to go for the second option i.e. the replace method.

You can make changes to your string saved in database to have placeholders like :cName and :depName and then replace these accordingly.

eval is not recommended visit for more on why?

Hope this helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
  • I think you misunderstood where the first "object" is coming from – Bravo Oct 10 '19 at 06:56
  • @Bravo from wherever the object is coming from. This is how object literals will work. As far as there are variables available it does not matter. And also i did mention that this is just for example and not exact solution as for that i will need a working demo showing what is exaclty required. Also if you can please explain the downvote? – Manish Oct 10 '19 at 07:09
  • really, so if you read that object from, say a database, which would store `"template": "This is ...."` ... you think creating an `obj` using `\`` is going to simulate the actual object the OP is working with? no, he states that the object is stored, in a database, as a string as per his question – Bravo Oct 10 '19 at 07:12
  • I think you still did not get my answer. I explained how object literals work and not the exact solution. If its stored in DB then `replace` will be the way to go. And yes my answer is not the solution for the OP's problem. But this helps him understand how template literals work and that surely will not work in his case – Manish Oct 10 '19 at 07:17
  • I get your answer - it relies on `obj.template` being a template literal .... retrieved from a database, it won't be - I think the OP is fully aware of how template literals work – Bravo Oct 10 '19 at 07:18
  • @Bravo have updated the answer to have a proper solution as per OP's problem with examples. Hope i'm correct this time. – Manish Oct 10 '19 at 07:30
  • does it work? then you are correct - despite using `eval` :p – Bravo Oct 10 '19 at 07:53
  • string.replace is the way. the OP will have to change the string stored to have placeholders to be replaced. `eval` is not recommended due to obvious reasons and in this specific case the string may have html tags hence the best recommended solution is to use `replace` by modifying the strings stored in database to have placeholder and replacing them when required. – Manish Oct 10 '19 at 08:02
-1

A template literal is ... literal. It is parsed at the moment JavaScript encounters it while parsing your code, and at that moment the referenced variables must be defined. As soon as you store a real template literal, it would already be parsed. For that reason, you cannot deal with template literals as if they were template variables. That concept does not exist in JavaScript, and so what you stored in the database has nothing to do with a template literal. It is a plain string, with dollars and braces.

If you want to still go ahead with storing the string like that in the database, you will have to parse the string yourself at the moment you know the variables that need to be merged into it.

let myDBObject = [{
  "classical" : "cs",
  "state" : "myState",
  "template" : "this is ${countryName} <b>Thanks for ${departmentName}</b>"
}];

function render(template, data) {
    return template.replace(/\$\{(\w+)\}/g, (_, name) => data[name] || "?");
}

console.log(render(myDBObject[0].template, { countryName: "India", departmentName: "science"}));
trincot
  • 317,000
  • 35
  • 244
  • 286