如何在不使用框架(例如ex = express)的情况下,将模板(手把或其他替代品)与Node.js一起使用? [英] How to use templating (handlebars, or any alternative) with Node.js and without using a framework (ex = express)?

查看:93
本文介绍了如何在不使用框架(例如ex = express)的情况下,将模板(手把或其他替代品)与Node.js一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example, I have this JSON document "foo.json":

{
    "foo": [
        {
            "bar": "Hello World!"
        },
        {
            "bar": "The End"
        }
    ]
}

在Node.js中,我想使用模板(把手或任何工具)从JSON文档生成字符串,例如:

In Node.js, I would like to use templating (handlebars or any) to generate a string from the JSON document, such as:

<p>Hello World!</p><p>The End</p>

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

... And then assign that string value to a variable in Node.js. Finally, I'll concatenate more values to the variable and output the final variable value as an html document.

可以在不使用Express之类的框架的情况下完成此操作吗?

Can this be done without using a framework like Express?

推荐答案

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

If you want to use handlebars, just grab the npm module:

npm install handlebars

然后在脚本中,您可以使用车把基于一个简单的模板渲染输出,该模板在数组foo上进行迭代,并为每个项目创建一个<p>,其中包含bar属性的文本:

Then in your script, you can use handlebars to render your output based on a simple template that iterates over the array foo and creates a <p> for each item, containing the text of the bar property:

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读取文件,在返回的缓冲区上调用toString(),并使用该文件来调用渲染函数.试试这个:

If you want to use a .hbs template file instead of a string source you can use the fs module to read the file with fs.readFile, call toString() on the returned buffer, and use that to call a rendering function. Try this:

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;
}

这篇关于如何在不使用框架(例如ex = express)的情况下,将模板(手把或其他替代品)与Node.js一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆