Sanny Singhs
Sanny Singhs

Reputation: 73

Formatting dates in Underscore templates

I have a date attribute in a Backbone model used in an underscore template.
The date value is in integer format like 123456432.

I want to show this integer value in dd / mm / yyyy format in an underscore template, like the way I do in PHP.

Here is my underscore template

<script type="text/template" id="item-template">    
    <span class="label label-info"><%- name %> <em> <%= date %> </em>  </span>
</script>

Upvotes: 2

Views: 13181

Answers (2)

nikoshr
nikoshr

Reputation: 33364

Underscore templates let you call function and output text in any way you see fit via print. For example, to convert your timestamp to a date, you could use something like this

<script type="text/template" id="tpl-1">    
    <span class="label label-info"><% print(new Date(date*1000)) %></span>
</script>

Note that I assume the timestamp comes from PHP, thus in seconds. In Javascript, the timestamps are expected to be in milliseconds, that's why I multiply it by 1000.

If your timestamps come from Javascript, use

<script type="text/template" id="tpl-1">    
    <span class="label label-info"><% print(new Date(date)) %></span>
</script>

Formatting this date object could be done like this

<script type="text/template" id="tpl-2">    
    <span class="label label-info"><% 
        var d = new Date(date*1000), // or d = new Date(date)
            fragments = [
                d.getDate(),
                d.getMonth() + 1,
                d.getFullYear()
            ]; 
            print(fragments.join('/'));
        %></span>
</script>

Or factorize all this into a function call (here on _.template but you could store it anywhere)

_.template.formatdate = function (stamp) {
    var d = new Date(stamp*1000), // or d = new Date(date)
        fragments = [
            d.getDate(),
            d.getMonth() + 1,
            d.getFullYear()
        ]; 
    return fragments.join('/');
};
<script type="text/template" id="tpl-3">    
    <span class="label label-info"><%= _.template.formatdate(date) %></span>
</script>

And a demo http://jsfiddle.net/Dyzm8/

Upvotes: 12

SoniCoder
SoniCoder

Reputation: 4174

You have 2 options:

When passing the result of the toJSON method, extend the object with another field:

var fields = this.model.toJSON();
fields.formattedDate = '29/11/1973';
this.template(fields);

The other way is to have a look at Backbone Marionette, which has helper methods for such cases (and solves many other repetitive tasks).

A simple PHP date function port in Javascript can be found here.

Upvotes: 0

Related Questions