Partials with Node.js + Express + Hogan.js
I've found a solution for the first question.
First of all, I removed hjs
:
npm remove hjs
Then, I installed the package hogan-express
:
npm install hogan-express
Furthermore, I edited app.js
:
/** * Module dependencies. */var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path');var app = express();app.engine('html', require('hogan-express'));app.enable('view cache');app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'html'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(require('less-middleware')({ src: __dirname + '/public' })); app.use(express.static(path.join(__dirname, 'public')));});app.configure('development', function(){ app.use(express.errorHandler());});app.get('/', routes.index);app.get('/users', user.list);http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port'));});
And routes/index.js
:
exports.index = function(req, res) { res.locals = { title: 'Title', }; return res.render( 'index', { partials: { part: 'part', } } );};
Now, in /views
there are index.html
, part.html
.The file part.html
contains:
<h1>{{ title }}</h1>
The file index.html
contains:
{{> part}}Hello world!
So, It works fine.
At least in Express 4+, partials just work out of the box. You can use express-generator (from npm) with --hogan or -H option.
After doing that, you need to add partials to the render method:
router.get('/', function(req, res, next) { res.render('index', { title: 'My Site', partials: {header: 'header'} });});
Then, in your template use {{ > xxx }}
<body> {{> header }} <h1>{{ title }}</h1> <p>Welcome to {{ title }}</p></body>
NOTE: this has header.hjs in views
To use partials with express+hogan, just do the following:
app.get('/yourRoute', function(req, res){ res.render('yourPartial', function(err,html){ var partialHTML = html; res.render('yourMainView', { myPartial: partialHTML }, function(err,html){ res.send(html); }); });}
And now, yourMainView.html:
<p>Something Something Something</p>{{{partialHTML}}}<p>Bla Bla Bla</p>
Notice the triple '{' instead of double as you usually do! That telling hogan (mustache) to parse this as HTML rather then a string!
That's it.