Question

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

Was it helpful?

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.

OTHER TIPS

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.

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}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top