I recently started programming on nodeJs.
I have different strings and Json Object;
eg :
var str = 'My name is {name} and my age is {age}.';
var obj = {name : 'xyz' , age: 24};
var str = 'I live in {city} and my phone number is {number}.';
var obj = {city: 'abc' , number : '45672778282'};
How do I automate this process, so using string and obj I will replace string {} value to obj (key value).
I have tried PUG but not able to parse.
pug.render(str, obj);
Doesn't work for me.
lets see, you want to make something like templating, just like handlebars http://handlebarsjs.com/.
I will give you this example to make a simple-handlebars for you case:
function render(template, properties)
{
var result = template;
for (i in properties)
{
result = result.replace("{"+i+"}",properties[i]);
}
return result;
}
but this one will only change first occurence of respective properties, if you want you may use this for replace all in the whole template:
function render(template, properties)
{
var result = template;
for (i in properties)
{
var reg = new RegExp("{"+i+"}","g");
result = result.replace(reg,properties[i]);
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With