How to use templating (handlebars, or any alternative) with Node.js and without using a framework (ex = express)?

半腔热情 提交于 2019-12-03 09:03:07

问题


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

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

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>

... 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.

Can this be done without using a framework like Express?


回答1:


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

npm install handlebars

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

--EDIT--

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


来源:https://stackoverflow.com/questions/23445339/how-to-use-templating-handlebars-or-any-alternative-with-node-js-and-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!