O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.11. Using a Complex Scripting Engine

Problem

You need to find a templating engine that supports number formatting, date formatting, and comparison of double values. In addition, you are looking for a templating engine that gives you more control over whitespace and line breaks.

Solution

Use FreeMarker, a templating engine with a large built-in feature set that includes support for date and number formatting and intelligent handling of whitespace. The following FreeMarker template creates a summary report for a college course:

<#assign student = enrollment.student > <#assign course = enrollment.course > <#assign exams = enrollment.exams > <#-- This macro assigns a variable named final --> <@final exams=exams/> ${student.firstName} ${student.lastName}, Here is a summary of your performance in ${course.dept} ${course.num} ${course.name}. Class: ${course.name} Professor: ${course.professor} Section: ${enrollment.section?string("000")} Exam, Date, Score, Weight, Grade ----------------------------------------------- <#list exams as exam> <@compress single_line=true> <#assign score = exam.score > ${exam.name}, ${exam.date?date?string.short}, #{exam.score; m1M1}, ${exam.weight}, <@letter score=score/> </@compress> </#list> Final Grade: ${final; m1M1} <@letter score=final/> Your final grade has been submitted to the Registrar. <#macro final exams> <#local num = 0> <#local dem = 0> <#list exams as exam> <#local num = num + (exam.score * exam.weight)/> <#local dem = dem + exam.weight> </#list> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required