Reputation: 23747
When I print the created_at field of a model using Backbone.js( <i> {{created_at}} </i>
), I'm getting: 2011-08-07T12:03:00Z
.
I'm trying to change the date to a readable format for hours and I'm not being able to.
I want the T and Z to be removed before printing.
thanks
Upvotes: 1
Views: 1641
Reputation: 3095
Readable? Why not jQuery timeago? jQuery timeago
In your Backbone model,
toTemplateData: ->
_.extend
created_duration: do => $.timeago @get("created_at") if @get("created_at")
In your Backbone view,
render: ->
@$el.html(@template(@model.toTemplateData() ))
In your template,
<time title="{{created_duration}}"></time>
Upvotes: 1
Reputation: 38428
Ben's answer is correct but the formatting of the date should really be in a model somewhere as it is business logic.
My variation of that would be:
render: function() {
var context = this.model.format().toJSON();
var html = this.template.to_html(context);
$(this.el).html(html);
}
And in your model, something like:
format() {
this.set('created_at_formatted', formatDate(this.get('created_at')));
return this;
}
formatDate: function(d) {
// format date stuff (See Ben`s answer)
return d;
}
And your template would render:
<i> {{created_at}} </i>
This removes some redundancy, promotes reuse and it is easier to read. Perhaps my answer needs a little work but hopefully you get the general idea.
Upvotes: 0
Reputation: 14725
Change the variable in your template context, or add a new one. I would add a new one.
If this is in your render function, it may be changed to something like this:
render: function() {
var context = this.model.toJSON();
context['created_at_formatted'] = this.formatDate(context['created_at']);
var html = this.template.to_html(context);
$(this.el).html(html);
}
With a function added to the view like this:
formatDate: function(d) {
var pad = function (n) {
return n < 10 ? '0' + n : n;
};
// in case the date is a string; you can remove this if you know it will be a date
if (typeof date === 'string') {
d = new Date(d);
}
return [
d.getUTCFullYear(), '-',
pad(d.getUTCMonth() + 1), '-',
pad(d.getUTCDate()), ' ',
pad(d.getUTCHours()), ':',
pad(d.getUTCMinutes()), ':',
pad(d.getUTCSeconds())
].join("");
}
Then the template would be like this:
<i> {{created_at_formatted}} </i>
To simplify the date formatting function, you could also use a date formatting library like DateJS. You could also move the date formatting to the model.
Upvotes: 2
Reputation: 46914
You can use the strftime on your created_at
<i> {{created_at.strftime('%Y/%m/%d')}} </i>
Upvotes: 0