Fork me on GitHub

Custom Freemarker configuration

Advanced usage of Freemarker

Freemarker is the templating language we are using for rendering views. It can do a lot of cool stuff, and you should refer to to learn more.

The Freemarker Configuration object can be accessed via your application TemplateEngineFreemarker singleton. According to the FreeMarker documentation, the configuration will be thread-safe once all settings have been set via a safe publication technique. Therefore, consider modifying it only within an extended NinjaDefault class, during the framework start.

package conf;

public class Ninja extends NinjaDefault {

	protected TemplateEngineFreemarker templateEngineFreemarker;

	public void onFrameworkStart() {

		Configuration freemarkerConfiguration = templateEngineFreemarker.getConfiguration();


Custom functions - The Java way

While you can access the Freemarker Configuration object, you can add your own custom functions using Java code:

freemarkerConfiguration.setSharedVariable("upper", new TemplateMethodModelEx() {

	public Object exec(List args) throws TemplateModelException {
		return new SimpleScalar(args.get(0).toString().toUpperCase());

And in your template:

${upper('Make me upper case.')}

Custom functions - The Ftl way

But for templating purpose, you can also do it by defining sets of macro functions in separate .ftl.html files.

<#macro bold>
	<b><#nested /></b>

And in your template :

<#import "../layout/functions.ftl.html" as f> 
<@f.bold>Make me bold</@f.bold>

This last way should help you making reusable macros when using one or another HTML/CSS framework.