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> ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.