Skip to content

Instantly share code, notes, and snippets.

@robashton
Created October 28, 2012 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robashton/3969285 to your computer and use it in GitHub Desktop.
Save robashton/3969285 to your computer and use it in GitHub Desktop.
Push-based dom templating with cheerio
<h1></h1>
<section>
<div class="hotel">
<h5 class="hotel-name"></h5>
<p class="hotel-description"></p>
</div>
</section>
<!-- Trying to use the HTML elements themselves as selectors will lead to pain because the designer should be able to change that crap and you shouldn't have to worry which elements they've used, classes/ids are saner -->
app.get('/', function(req, res) {
db.getListOfHotels(function(err, data) {
res.render('index', {
region: 'Paris',
hotels: data
})
})
})
;
var $ = require('cheerio')
function renderView(filename, model, res) {
lookupView(filename, function(err, html) {
var manipulated = $(html)
var presenter = getPresenterForView(filename)
presenter(manipulated, model)
res.end(manipulated.html())
})
}
;
function indexPresenter($el, model) {
$el.find('h1').text('List of hotels in ' + model.region)
var $hotelTemplate = $el.find('.hotel')
var $hotelContainer = $el.find('section')
for(var i =0 ; i < model.hotels ; i++) {
hotelPresenter($hotelTemplate, model.hotels[i])
$hotelContainer.append($hotelTemplate.clone())
}
}
function hotelPresenter($hotel, model) {
$('.hotel-name').text(model.hotelName)
$('.hotel-description').html(model.hotelDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment