我是freemarker的初学者,我想用它来生成一些重复的代码。
从像这样的简单类:
public class Point {
private Integer x;
private Integer y;
private String name;
}
我需要为每个属性生成如下所示的行:
ValueProvider<Point,Integer> x();
ValueProvider<Point,Integer> y();
ValueProvider<Point,String> name();
为实现这一目标,我有这个简单的模板:
ValueProvider<${clazz},${attrType}> ${attrName}();
然后,我想生成一个完整的类:
public final class PointValueProviders {
public interface PointPropertyAccess extends PropertyAccess<Point>{
ValueProvider<Point,Integer> x();
ValueProvider<Point,Integer> y();
ValueProvider<Point,String> name();
}
public static final PointPropertyAccess POINT_PA= GWT.create(PointPropertyAccess.class);
private PointValueProviders(){}
};
为此,我遇到了一个问题:我不知道如何在较大的模板中应用不确定次数的小模板,如下所示:
public final ${clazz}ValueProviders {
public interface ${clazz}PropertyAccess extends PropertyAccess<${clazz}>{
//Here, How do I tell freemarker to use the small template???
//ValueProvider<${clazz},${attrType}> ${attrName}();
//ValueProvider<${clazz},${attrType}> ${attrName}();
//ValueProvider<${clazz},${attrType}> ${attrName}();
//ValueProvider<${clazz},${attrType}> ${attrName}();
//etc..
}
public static final ${clazz}PropertyAccess ${clazzUpperCase}_PA= GWT.create(${clazz}PropertyAccess.class);
private ${clazz}ValueProviders(){}
};
有什么想法吗?
答案 0 :(得分:1)
模板将显示您提供给他们的一些数据。所以重要的问题是,模板如何知道要输出的class
/ attrType
/ attrName
三重奏?你应该提供一个列表,我们称之为props
,然后用
<#list props as prop>
ValueProvider<${prop.clazz},${prop.attrType}> ${prop.attrName}();
</#list>
否则,要创建小型可重复使用模板,请使用#macro
(这一个更灵活)或#include
。请参阅FreeMarker Manual。