Search code examples
javascriptdust.jsclient-side-templating

Format Numbers and Dates in dust.js (linkedin-fork)


How can i format numbers, currency or date values within a dust.js template?

Data:

{
today: 'Wed Apr 03 2013 10:23:34 GMT+0200 (CEST)'
}

Template:

<p>Today: {today} </p>

Like this way: (with moment.js)

<p>Today: {moment(today).format('dd.MM.YYYY')}</p>

Or round some price-values*

Data: { price: 56.23423425 }

Template:

Price: {price.toFixed(2)}


Solution

  • You are probably going to need to write a helper. Details on how to write a helper can be found here:

    Your template for a Date string would look like this:

    <p>Today: {@formatDate value="{today}"/}</p>
    

    Your helper would be something like this:

    dust.helpers.formatDate = function (chunk, context, bodies, params) {
        var value = dust.helpers.tap(params.value, chunk, context),
            timestamp,
            month,
            date,
            year;
    
        timestamp = new Date(value);
        month = timestamp.getMonth() + 1;
        date = timestamp.getDate();
        year = timestamp.getFullYear();
    
        return chunk.write(date + '.' + month + '.' + year);
    };
    

    You would want to add in the piece to get the leading zero in front of the month or date as well.