简体   繁体   中英

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!

Keep it simple.

function template(data) {

  var object = {
    'sts': data[0].sts,
    'msg': data[1].msg
  };

  return object;

}

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

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

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'
  }
}
*/

I've been pretty happy with jQuery's new templating engine:

http://api.jquery.com/category/plugins/templates/

You can use jQuery.extend() to merge the data fragments prior to filling out the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM