简体   繁体   English

JSON模板引擎

[英]JSON templating engine

Is there any JSON templating engine? 有没有JSON模板引擎? 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: 如果你从JSON转到JSON,你可以使用Javascript,只需颠倒分配顺序:

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. JSON.stringify在大多数现代浏览器中都可用作本机对象和方法。 If not you can use json2.js 如果没有,你可以使用json2.js

But if you need a template engine to convert JSON to HTML, you can have a look at pure.js 但是,如果您需要模板引擎将JSON转换为HTML,您可以查看pure.js

Yes, there exists a JSON templating engine. 是的,存在一个JSON模板引擎。 I don't know what you need, but json-templater is an option. 我不知道你需要什么,但是json-templater是一个选择。

template.json: 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: 我对jQuery的新模板引擎非常满意:

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

You can use jQuery.extend() to merge the data fragments prior to filling out the template. 您可以在填写模板之前使用jQuery.extend()合并数据片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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