例如,我有这个 JSON 文档“foo.json”:
{
"foo": [
{
"bar": "Hello World!"
},
{
"bar": "The End"
}
]
}
在 Node.js 中,我想使用模板(handlebars 或任何模板)从 JSON 文档生成字符串,例如:
<p>Hello World!</p><p>The End</p>
...然后将该字符串值分配给 Node.js 中的变量。最后,我会将更多值连接到变量并将最终变量值输出为 html 文档。
不使用像 Express 这样的框架可以做到这一点吗?
如果你想使用把手,只需获取 npm 模块:
npm install handlebars
然后在您的脚本中,您可以使用句柄基于迭代数组的简单模板来渲染输出foo
并创建一个<p>
对于每个项目,包含的文本bar
财产:
var handlebars = require('handlebars');
// get your data into a variable
var fooJson = require('foo.json');
// set up your handlebars template
var source = '{{#each foo}}<p>{{this.bar}}</p>{{/each}}';
// compile the template
var template = handlebars.compile(source);
// call template as a function, passing in your data as the context
var outputString = template(fooJson);
如果您想使用 .hbs 模板文件而不是字符串source
你可以使用fs
读取文件的模块fs.readFile
, call toString()
返回的缓冲区上,并使用它来调用渲染函数。尝试这个:
var handlebars = require('handlebars');
var fs = require('fs');
// get your data into a variable
var fooJson = require('path/to/foo.json');
// read the file and use the callback to render
fs.readFile('path/to/source.hbs', function(err, data){
if (!err) {
// make the buffer into a string
var source = data.toString();
// call the render function
renderToString(source, fooJson);
} else {
// handle file read error
}
});
// this will be called after the file is read
function renderToString(source, data) {
var template = handlebars.compile(source);
var outputString = template(data);
return outputString;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)