19

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
  • Seems like you're going to write a static website generator or something like that. Checkout assemble.io - it's awesome and it uses handlebars for templating.
    – hgoebl
    May 3, 2014 at 15:10

1 Answer 1

47

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

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;
}
3
  • Is there a way to add the "source" variable value (from your example) to a separate file and make it multi-line (ex = add an h1 tag on it's own line and above the p tag)?
    – edt
    May 3, 2014 at 14:29
  • 1
    Yep, you can use a regular .hbs file. I updated the answer to show how to do that.
    – jshanley
    May 3, 2014 at 14:48
  • just needed the .toString() from this answer. Thanks Sep 19, 2017 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.