如何使用Node.js的模板(把手或任何替代方案)而不使用框架(ex = express)?

edt*_*edt 14 node.js handlebars.js

例如,我有这个JSON文档"foo.json":

{
    "foo": [
        {
            "bar": "Hello World!"
        },
        {
            "bar": "The End"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

在Node.js中,我想使用模板(handlebars或any)从JSON文档生成一个字符串,例如:

<p>Hello World!</p><p>The End</p>
Run Code Online (Sandbox Code Playgroud)

...然后将该字符串值分配给Node.js中的变量.最后,我将更多值连接到变量,并将最终变量值输出为html文档.

这可以在不使用像Express这样的框架的情况下完成吗?

jsh*_*ley 35

如果你想使用把手,只需抓住npm模块:

npm install handlebars
Run Code Online (Sandbox Code Playgroud)

然后在您的脚本中,您可以使用把手基于一个简单的模板来渲染输出,该模板遍历数组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);
Run Code Online (Sandbox Code Playgroud)

- 编辑 -

如果要使用.hbs模板文件而不是字符串source,可以使用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;
}
Run Code Online (Sandbox Code Playgroud)