Thursday, April 9, 2015

Date Formatting with Sightly


Now that more and more peo­ple doing Sightly imple­men­ta­tions an often heard ques­tion is how to do Date-formatting in Sightly.
In this small blog­post I will show you a way to achieve that.
 In the exam­ple below I will for­mat the last-modified date of the page, dis­play­ing it in a for­mat of dd/MM/yyyy.
I use Sling mod­els for this together with the Sim­ple­Date­For­mat 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 ‘invok­ing’ the tem­plate defined with the name ‘dateFormat’.
The tem­plate receives two para­me­ters, date and date­For­mat. In the tem­plate itself a Java-class is used, and that Java-class gets two para­me­ters date and dateFormat.
From the Java-class the value ‘for­mat­ted­Value’ is avail­able and it printed.
The code of the Java-class is avail­able 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 sim­ple because date and date­For­mat get injected auto­mat­i­cally. There­fore the only ‘real’ code you need to do is only to call the format()-method.
Hope­fully this gives you an idea how to do for­mat­ting with Sightly.

No comments: