Is there any JSON templating engine? I'm looking for something like this...
var template = {
'sts': '%data1.sts%',
'msg': '%data2.msg%'
};
var data1 = {
'sts': 200
};
var data2 = {
'msg': 'Hi!'
};
// render(template, [data sources]);
var response = render(template, [data1, data2]);
console.log(response);
Output
{
'sts': 200,
'msg': 'Hi!'
}
Thanks for reply!
Take a look at mustache. It appears to be what you are after.
Yes, there exists a JSON templating engine. I don't know what you need, but json-templater is an option.
template.json:
{
"magic_key_{{magic}}": {
"key": "interpolation is nice {{value}}"
}
}
======== Your code that uses the template ========
var object = require('json-templater/object');
var result = object(
require('./template.json'),
{ magic: 'key', value: 'value' }
);
console.log(result);
/* should look something like this:
{
magic_key_key: {
key: 'interpolation is nice value'
}
}
*/
If you go from JSON to JSON, you can stay with Javascript, and just reverse the order of assignments:
var data1 = {
sts: 200
};
var data2 = {
msg: 'Hi!'
};
var template = {
sts: data1.sts,
msg: data2.msg
};
console.log( JSON.stringify(template) ); //--> {"sts":200,"msg":"Hi!"}
JSON.stringify
is available on most modern browsers as a native object and methode. If not you can use json2.js
But if you need a template engine to convert JSON to HTML, you can have a look at pure.js
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