开发者

Creating your own custom helpers with Freemarker?

From my controller I set my Model and view like:

ModelAndView mav = new ModelAndView();

mav.setView("index");

mav.addObject("user", user);
mav.addObject("someCollection", someCollection);

return mav;

Now I want to create a helper type object that will take the someCollection and the user object as paramet开发者_Go百科ers.

My helper function will output some HTML etc., is this possible?


You can write macros and directives using FTL or Java, expose them to your templates and invoke them same way you normally do with built-in macros/directives.


Nothing prevents you from putting any Java object, e.g. a helper instance, to the model and then call a method of it using the syntax like this: ${helper.myMethod(arg)}.


/**
 * Add logotype logotype1AsBase64.
 * @return
 * @throws IOException 
@ModelAttribute("logotype1AsBase64")
public String getLogotype() 
        throws IOException {
    return logotypeService.getLogotype();
}
*/

@ModelAttribute
public void addAttributes(Model model) throws IOException {
    //...
    model.addAttribute("logotype1AsBase64", logotypeCacheServ.getImage("logotypeInEnglish1From20190101.png"));
    //...
}

Then to use it:

<img src="<#if locale == 'specificLocale'>${logotype1AsBase64}></#if>" alt="description for picture">

And the model attribute can contain more html other than base64 for logotype, if the setup is as such.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜