Freemarker - access to object static variables

I have a simple class:

public class MyClass { public final static long MAIN = 1; @Setter @Getter protected int id; } 

( @Setter @Getter are @Getter annotations for the Setter and Getter methods.)

In the Freemarker template, I would like to create a condition like:

 <#if myClassInstance.id == myClassInstance.MAIN> 

But the right side of the if matches FreeMarker undefined. Is there any way to do this? Thanks!

+4
source share
3 answers

The template language does not know Java classes. But you can open static elements through a data model (template context). See: http://freemarker.org/docs/pgui_misc_beanwrapper.html#autoid_55

+2
source

I know this question already has an accepted answer, but I'm still writing a piece of code that might be useful to someone else.

Use below code snippet in java

 BeansWrapper w = new BeansWrapper(); TemplateModel statics = w.getStaticModels(); map.put("statics", statics); // map is java.util.Map template.process(map, out); // template is freemarker.template.Template 

Then the access constant in ftl

 ${statics["com.model.to.gen.Common"].FLAG_YES} 

here com.model.to.gen.Common is a class, and FLAG_YES is a static constant.

+2
source

You can use the option to set fields . This way you can use data models without accessories (getters / seters).

 BeansWrapperBuilder wrapperBuilder = new BeansWrapperBuilder(Configuration.VERSION_2_3_23); wrapperBuilder.setExposeFields(true); Template template = freemarkerConfiguration.getTemplate("mytemplatefile.ftl"); StringWriter stringWriter = new StringWriter(); template.process(model, stringWriter, wrapperBuilder.build()); System.out.println(stringWriter.toString()); 
0
source

Source: https://habr.com/ru/post/1400903/


All Articles