Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freemarker: call a static util method from a template file (*.ftl)

Tags:

freemarker

In a Freemarker FTL file, I want to call StringUtils.capatilize(myString). For example:

<p>You selected ${selectionString}.</p>
<p>${StringUtils.capatilize(selectionString)} is great.</p>

Can I somehow import org.apache.commons.lang3.StringUtils?

like image 260
Geoffrey De Smet Avatar asked Aug 22 '16 14:08

Geoffrey De Smet


2 Answers

First, add these code to your Controller:

BeansWrapper wrapper = new BeansWrapper(new Version(2,3,27));
TemplateModel statics = wrapper.getStaticModels();
model.addAttribute("statics", statics);

And then, in your .ftl file, define the class like this:

<#assign YourUtilClass=statics['com.springboot.util.YourUtilClass']>

(The path including in [''] is the class' path)
Finally, you can access your static method like this:

${YourUtilClass.yourMethod(someParams)}
like image 117
Juan Chan Avatar answered Oct 15 '22 14:10

Juan Chan


You can't #import a class, only other templates.

Note that you can achieve a similar result with #assign StringUtils=statics['org.apache.commons.lang3.StringUtils'], as far as you add objectWrapper.getStaticModels() as statics to the set of shared variables in the Configuration or add it to the data-model.

like image 45
ddekany Avatar answered Oct 15 '22 15:10

ddekany