简体   繁体   English

Freemarker:根据对象字段动态生成内容

[英]Freemarker: Dynamically generate content based on object fields

I am new to Freemarker. 我是Freemarker的新手。 I want to dynamically generate the content in FTL, so that it will display all the fields in the object. 我想在FTL中动态生成内容,以便它将显示对象中的所有字段。 In Java we can achive this through reflection. 在Java中,我们可以通过反射来实现。 Not sure in Free marker. 不确定免费标记。

Example: 例:

class Employee{
String name;
String age;

//setter and getter methods
}

class Organization{
String orgName;
String location;

//setter and getter methods.
}

I want to write common ftl file which will display all the objects fields irrespective of data types. 我想编写通用的ftl文件,该文件将显示所有对象字段,而与数据类型无关。

I do not want to write in as below. 我不想写如下。 I want it to be generic. 我希望它是通用的。

<td><div>${employee.name!}</div></td>
<td><div>${employee.age!}</div></td>

Any help will be really appreciated. 任何帮助将不胜感激。

employee?keys should give you the JavaBeans property names, if you set up FM to not expose the methods too... Or if it does, you can use employee[propertyName]?is_method to filter them out. employee?keys应该给您JavaBeans属性名,如果您将FM设置为不公开方法的话...否则,您可以使用employee[propertyName]?is_method过滤掉它们。 You can use employee[propertyName] to read the property value. 您可以使用employee[propertyName]读取属性值。

However, I'm pessimistic about doing these things so automatically in general. 但是,我对通常如此自动执行这些操作感到悲观。 There will be always some properties that are too technical to print (like there's class just for starters), that has some funny type that FreeMarker won't convert to string properly or at all... If this kind of functionality is truly important in your project, you may want to mark those properties with annotations and then write TemplatMethodModelEx that gives you the names (and the other attributes needed for proper formatting etc.), or maybe a custom ObjectWrapper for the same purpose. 总是会有一些属性太过技术而无法打印(例如仅针对入门者的class ),它们具有一些有趣的类型,FreeMarker不会正确地或根本不会将其转换为字符串...如果这种功能在你的项目,你可能要标记与注释的属性,然后写TemplatMethodModelEx ,让你的名字(和需要的格式正确等其他属性),或者一个定制ObjectWrapper为了同样的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM