Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)}

like image 688
tiefenb Avatar asked Apr 03 '13 08:04

tiefenb


3 Answers

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

  • https://github.com/linkedin/dustjs/wiki/Dust-Tutorial#wiki-Writing_a_dust_helper

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.

like image 192
jamie young Avatar answered Nov 15 '22 01:11

jamie young


For people that need to do this for a nodeJs application, here's a nice KrakenJS example:

https://github.com/lmarkus/Kraken_Example_Date_Format_Helper

It uses Moment.js to avoid reinventing the wheel on date formatting.

like image 39
Lenny Markus Avatar answered Nov 15 '22 01:11

Lenny Markus


You can write a filter to use moment. put sth like this: dust.filters.formatDate = (value) => moment.utc(value).format('l H:mm'); where proper in your script. then in your html, just put | beside your value: {date|formatDate}

like image 30
Ben Ji Avatar answered Nov 15 '22 00:11

Ben Ji