I want to apply some templates to JSON data (eventually will be getting the data from a url) using hbs and express. As a newbie using express 4, I found a lot of previous posts and solution really confusing as some functions are depreciated in express 4. I combined some snippets of codes and got a result like this:
var engines = require('consolidate');
var express = require('express');
var hbs = require('hbs');
app = express();
app.set('views', __dirname+ '/views');
app.set('view engine', 'hbs');
app.set("view options", { layout: true });
// ROUTES
app.get('/', function (req, res){
var data = {"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
res.render('index', JSON.stringify(data));
});
app.listen(3000);
I have also tried just putting a simple string in res.render, such as
res.render('index', 'haha');
But it still doesn't work. Any insights please..?
EDITED: The directory of my template is
views
- index.hbs
and I actually only put
<hi> Hi </h1>
in this file.
The second parameter of render is an object, not a string. Just pass data.
Edit: You're also setting layout: true but you don't have a layout.hbs. Set it to false and your index.hbs should render.
Edit2: Full working example
index.js
var engines = require('consolidate');
var express = require('express');
var hbs = require('hbs');
app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
app.set("view options", { layout: false });
// ROUTES
app.get('/', function (req, res){
var data = {
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
};
res.render('index', data);
});
app.listen(3000);
views/index.hbs
{{#each employees}}
Name: {{firstName}}<br>
{{/each}}