Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freemarker print date in template

I am trying to print the current date when the template is activated. I have read that I have to pass a new Date() Java object to the template, but I don't know how to do that or where to put it in the code.

Does someone know how to pass a Java object to the template in this case?

Thank you !!

like image 493
user763222 Avatar asked May 20 '11 18:05

user763222


2 Answers

Actually you don't have to pass a new Date() to your template, because placing a timestamp into a template's output is quite common and therefore FreeMarker provides a special variable called .now which returns the current date and time. You can use it in your template like this:

Page generated: ${.now}

(FreeMarker also contains different built-ins for formatting dates: http://freemarker.org/docs/ref_builtins_date.html)

Update: Works only with the latest version of FreeMarker, 2.3.17.

like image 121
Chaquotay Avatar answered Oct 17 '22 17:10

Chaquotay


Use the ObjectConstructor API of Freemarker to create a calendar object and a formatter object, then combine the two to print the date:

<#-- Create constructor object -->
<#assign objectConstructor = "freemarker.template.utility.ObjectConstructor"?new()>

<#-- Call calendar constructor -->
<#assign clock = objectConstructor("java.util.GregorianCalendar")>

<#-- Call formatter constructor -->
<#assign mmddyy = objectConstructor("java.text.SimpleDateFormat","MM/dd/yyyy")>

<#-- Call getTime method to return the date in milliseconds-->
<#assign date = clock.getTime()>

<#-- Call format method to pretty print the date -->
<#assign now = mmddyy.format(date)>

<#-- Display date -->
${now}

The ?new built-in, as it was implemented, was a security hole. Now, it only allows you to instantiate a java object that implements the freemarker.template.TemplateModel interface. If you want the functionality of the ?new built-in as it existed in prior versions, make available an instance of the freemarker.template.utility.ObjectConstructor class to your template. For example:

myDataModel.put("objConstructor", new ObjectConstructor());

and then in the template you can do this:

<#assign aList = objConstructor("java.util.ArrayList", 100)>)

References

  • Freemarker 2.3: Version History

  • Tag Developers Guide: Freemarker

  • CRUD Operations using Servlet and FreeMarker Template Engine

like image 35
Paul Sweatte Avatar answered Oct 17 '22 16:10

Paul Sweatte