繁体   English   中英

node.js中的json模板引擎

[英]json template engine in node.js

我有一个像下面这样的json模板:

[
  {
    "type":"foo",
    "config":"{config}"
  },
  {
    "type":"bar",
    "arrConfig":"{arrConfig}"
  }
]

虽然我有一个像这样的支持模型:

{
  "config": {
    "test1": "value1",
    "test2": "value2"
  },
  "arrConfig": [
    "test3": {
      "key1": "val1"
    },
    "test4": {
      "key1": "val1"
    }
  ]
}

我想知道是否有任何节点模块可以自动使用这两个节点模块并转换模板中的占位符。 因此输出如下所示:

[
  {
    "type":"foo",
    "config":{
      "test1": "value1",
      "test2": "value2"
    }
  },
  {
    "type":"bar",
    "arrConfig": [
      "test3": {
        "key1": "val1"
      },
      "test4": {
        "key1": "val1"
      }
    ]
  }
]

JSON.stringify接受您可以用来执行的JSON.stringify参数。

这应该工作:

var template = [
  {
    "type":"foo",
    "config":"{config}"
  },
  {
    "type":"bar",
    "arrConfig":"{arrConfig}"
  }
];


var data = {
  "config": {
    "test1": "value1",
    "test2": "value2"
  },
  "arrConfig": {
    "test3": {
      "key1": "val1"
    },
    "test4": {
      "key1": "val1"
    }
  }
};

var replacer = function (key, val) {
   if (typeof val === 'string' && val.match(/^{(.+)}$/)) {
     return data[val.replace(/[{|}]/g, '')]
   }
   return val;
 }

 console.log(JSON.stringify(template, replacer));

如果要将其转换回对象,则可以使用JSON.parse

这是一个遍历对象层次结构并替换指定模板字符串的函数:

 // modifies the object passed, and returns the same object function applyTemplate(template, backing) { for (var i in template) { var m = /^{(.+)}$/.exec(template[i]); if (m && backing[m[1]]) { // replace with a deep clone of the value from the backing model template[i] = JSON.parse(JSON.stringify(backing[m[1]])); } else if (template[i] && "object" == typeof template[i]) { // traverse down recursively applyTemplate(template[i], backing); } } return template; } var template = [ { "type":"foo", "config":"{config}" }, { "type":"bar", "arrConfig":"{arrConfig}" } ]; var backing = { "config": { "test1": "value1", "test2": "value2" }, "arrConfig": { "test3": { "key1": "val1" }, "test4": { "key1": "val1" } } }; applyTemplate(template, backing); console.log(JSON.stringify(template, null, 2)); 

加上使用原始JSON文本替换的概念验证( 不可靠,请不要实际使用 ;但适用于绝大多数情况):

function applyTemplateStr(template, backing) {
  template = JSON.stringify(template);
  for (var key in backing) {
    template = template.split('"{'+key+'}"').join(JSON.stringify(backing[key]));
  }
  return JSON.parse(template);
}

您可以使用Mustache ,如下所示:

var template = [
  {
    type: "foo",
    config: "{{config}}"
  }
];

var data = {
  config: "hello"
};

const Mustache = require("mustache");

function render(template, data) {
  return Mustache.render(JSON.stringify(template), data);
}

var output = render(template, data);
console.log(output);  // [{"type":"foo","config":"hello"}]

暂无
暂无

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

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