mustache.js date formatting

Dooie picture Dooie · Apr 8, 2012 · Viewed 25.6k times · Source

I have started using mustache.js and so far I am very impressed. Although two things puzzle me. The first leads on to the second so bear with me.

My JSON

{"goalsCollection": [
    {
        "Id": "d5dce10e-513c-449d-8e34-8fe771fa464a",
        "Description": "Multum",
        "TargetAmount": 2935.9,
        "TargetDate": "/Date(1558998000000)/"
    },
    {
        "Id": "eac65501-21f5-f831-fb07-dcfead50d1d9",
        "Description": "quad nomen",
        "TargetAmount": 6976.12,
        "TargetDate": "/Date(1606953600000)/"
    }
]};

My handling function

function renderInvestmentGoals(collection) {
    var tpl = '{{#goalsCollection}}<tr><td>{{Description}}</td><td>{{TargetAmount}}</td><td>{{TargetDate}}</td></tr>{{/goalsCollection}}';
    $('#tblGoals tbody').html('').html(Mustache.to_html(tpl, collection));
}

Q1 As you can see my 'TargetDate' needs parsing but I am unsure of how to do that within my current function.

Q2 Say I wanted to perform some function or formatting on one or more of my objects before rendering, what is the best way of doing it?

Answer

McGarnagle picture McGarnagle · Apr 8, 2012

You can use a "lambda"

"TargetDate": "/Date(1606953600000)/",
"FormatDate": function() {
    return function(rawDate) {
        return rawDate.toString();
    }
}, ...

Then in the markup:

<td>
{{#FormatDate}}
    {{TargetDate}}
{{/FormatDate}}
</td>

From the link:

When the value is a callable object, such as a function or lambda, the object will be invoked and passed the block of text. The text passed is the literal block, unrendered.