Last active
December 14, 2015 07:19
-
-
Save simonmcmanus/5049489 to your computer and use it in GitHub Desktop.
An example of using Blend.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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