i've got this object
{ title: 'A TITLE',
description: 'Lorem Ipsum...',
_id: 50806930bbf612a858000013,
__v: 0,
screenings:
[ { venue: 'Venue1', dates: [Object] },
{ venue: 'Venue2', dates: [Object] } ] }
coming out of my mongoDB.
dates
is a list of dates (dah!).
My issue is now I want to have them formatted with momentjs server-side.
It would look like I should be using mustache lambdas, but it appears impossible using my stack (expressjs, consolidate, handlebars...)
Anybody solved this?
Here's what I'm trying now
Theatre.find({"screenings.dates":{$gte:lastSunday, $lte:nextSunday}}, function(err, entities){
res.render('index', {
entities: entities,
giveitatry: function(a) {
return moment(a).format("MMM Do YY")
}
});
});
and on my template I have:
{{#entities}}
<div class="span3">{{#giveitatry}} {{dates.0.}} {{/giveitatry}}</div>
{{/entities}}
Here's part of the expressjs conf
var moment = require('moment');
var express = require('express')
, cons = require('consolidate')
, name = 'mustache';
app.configure(function(){
app.set('view engine', 'hjs');
app.engine('.hjs', cons.mustache);
...
yes, extension's still hjs 'cause i started using hogan but i wasn't able to do it with hogan so i moved to consolidate+mustache.
i'm using node v0.8.8 and expressjs 3.0.0rc4
If you use mustache.js lambdas, you need to return a function instead. The parameters for this function are text
, which contains textual representation of the template content and render
that can be explicitly invoked to render the template.
The best solution I have found so far is that you first use the default renderer, then pass the resulting date string back to a constructor of new Date
object, which then is further passed to moment
function. Finally you just return the date with desirated formatting.
Full code:
giveitatry: function() {
return function(text, render) {
var date = moment(new Date(render(text)));
return date.format("MMMM Do YY");
}
}
Works similarly well for lists of dates:
{{#entities}}
{{#dates}}
<div class="span3">{{#giveitatry}}{{.}}{{/giveitatry}}</div>
{{/dates}}
{{/entities}}
You are not alone in this problem. The introduction for helpers / filters that would provide a cleaner solution to this problem is ongoing in mustache.js's issue tracker (see [1], [2]).