Date Formatting with Sightly
Now that more and more people doing Sightly implementations an often heard question is how to do Date-formatting in Sightly.
In this small blogpost I will show you a way to achieve that.
In the example below I will format the last-modified date of the page, displaying it in a format of dd/MM/yyyy.
I use Sling models for this together with the SimpleDateFormat class.
<div data-sly-call="${ dateFormat @ date=currentPage.lastModified, dateFormat='dd/MM/yyyy' }"></div> <template data-sly-template.dateFormat="${ @ date, dateFormat }"> <div data-sly-use.formatter="${'com.yourproject.DateFormatting' @ date=date,dateFormat=dateFormat}"> Formatted value : ${formatter.formattedValue} </div> </template>
With data-sly-call I am ‘invoking’ the template defined with the name ‘dateFormat’.
The template receives two parameters, date and dateFormat. In the template itself a Java-class is used, and that Java-class gets two parameters date and dateFormat.
From the Java-class the value ‘formattedValue’ is available and it printed.
The code of the Java-class is available here.
@Model(adaptables=SlingHttpServletRequest.class) public class DateFormatting { @Inject private Calendar date; @Inject private String dateFormat; public String formattedValue; @PostConstruct protected void init() { SimpleDateFormat formatter = new SimpleDateFormat(dateFormat); formattedValue = formatter.format(date.getTime()); } }
The code in the Java-class is quite simple because date and dateFormat get injected automatically. Therefore the only ‘real’ code you need to do is only to call the format()-method.
Hopefully this gives you an idea how to do formatting with Sightly.
No comments:
Post a Comment