Search code examples
javafreemarker

How to use Locale in freemarker template


I am very new to free marker , I having an issue , I want to create a PDF using ftl , there I need to show the data as per locale ,data I want to format as per locale is (double)amount. e.g

   DataDto{
      double amount;
   }

Now I want to show this data in pdf as per locale e.g. for fi_FI 1.00 -> 1,00 and for us_US 1.00 -> 1.00. I checked this and this and this too, but did not get any solid answer.. I tried to make method in dto which will return the formatted number as string but when tried to call this method in ftl got the error like InvalidReferenceException. I am not getting any way to get it done , Is there any way we can achieve this like can we using something is setting directives if I define locale in dto class and get it in ftl. or can call the method in ftl.

${data.amount?string("${data.locale}")} gives current locale-> en I dont know how to do it right

Any lead would be appreciated:) Thank you !


Solution

  • Ideally, the Java code that calls FreeMarker sets the locale setting to the desired locale (via the FreeMarker settings API, like Environment.setLocale(locale) for single template processing), and you have to do nothing in the template itself. Numbers by default are formatted for human audience, which is already locale sensitive.

    If, for whatever reason, you can't achieve that (like you aren't developing the Java code, and those who do can't be reasoned with), then you can set the locale in the template too with the #setting directive. For example:

    <#setting locale="en_US">
    ${3.14}
    <#setting locale="fi_FI">
    ${3.14}
    

    will print:

    3.14
    3,14