Skip to content

Instantly share code, notes, and snippets.

@simonmcmanus
Last active December 14, 2015 07:19
Show Gist options
  • Save simonmcmanus/5049489 to your computer and use it in GitHub Desktop.
Save simonmcmanus/5049489 to your computer and use it in GitHub Desktop.
An example of using Blend.
app.use(function(req, res, next) {
res.blend = function(params) {
params.buildData(params.params, function(e, d) {
if(req.headers['content-type'] === 'application-json') {
res.json(d);
} else { // render html
params.buildSelectors(d, function(selectors) {
var options = {
layout: (req.param('_pjax')) ? null : params.layout,
container: params.container || '#container',
selectors: selectors
};
if(req.headers['content-type'] === 'blend') {
res.json({
template: params.template,
selectors: options
});
}else {
res.render(params.template, options);
}
});
}
});
};
next();
});
/*
Blend middleware for Express.js
Exposes not only the data but also the object which would get passed to the templating language so that we can do the rendering in the browser.
An example usage:
*/
res.blend({
buildData: function(params, callback) {
// return all data required to load the page in the callback.
db.getData(params.id, callback;
},
buildSelectors: function(data, callback) {
// convert data into object to be passed to templating engine.
var selectors = {};
selectors['.username'] = req.session.username;
selectors['#widgets'] = {
partial: 'target',
data: sizlate.classifyKeys(data, {classifyKeys: true })
};
return callback(selectors);
},
template: 'targets',
layout: 'layout'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment