如何使用模板(句柄,或任何替代)与Node.js,而不使用框架(EX =明确)?
例如,我有这个JSON文件“foo.json”:
{ "foo": [ { "bar": "Hello World!" }, { "bar": "The End" } ] }
在Node.js中,我想使用模板(句柄或任何)从JSON文档生成一个string,如:
<p>Hello World!</p><p>The End</p>
…然后将该string值分配给Node.js中的一个variables。 最后,我将连接更多的值到variables,并将最终的variables值作为html文档输出。
这可以做到不使用Express之类的框架吗?
如果你想使用句柄,只需抓住npm模块:
npm install handlebars
然后在你的脚本中,你可以使用句柄来渲染你的输出,它是基于一个遍历数组foo
的简单模板,并为每个项目创build一个<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模板文件而不是stringsource
,可以使用fs
模块使用fs.readFile
读取文件,在返回的缓冲区上调用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; }