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

3

6

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

Bryner answered 3/4, 2013 at 8:27 Comment(0)
E
8

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.

Everyway answered 5/4, 2013 at 22:6 Comment(0)
R
3

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.

Renteria answered 6/1, 2014 at 7:20 Comment(0)
W
1

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}

Weatherworn answered 23/2, 2017 at 2:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.