Geoffrey De Smet
Geoffrey De Smet

Reputation: 27322

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

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

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

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

Upvotes: 12

Views: 10739

Answers (2)

Reed Chan
Reed Chan

Reputation: 555

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)}

Upvotes: 19

ddekany
ddekany

Reputation: 31152

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.

Upvotes: 5

Related Questions