Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON templating engine

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!

like image 518
Latanmos Avatar asked Jan 02 '11 21:01

Latanmos


3 Answers

Take a look at mustache. It appears to be what you are after.

like image 93
karim79 Avatar answered Nov 01 '22 08:11

karim79


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'
  }
}
*/
like image 41
Stucco Avatar answered Nov 01 '22 10:11

Stucco


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

like image 1
Mic Avatar answered Nov 01 '22 09:11

Mic