2013-05-27 186 views
0

我是freemarker的初學者,我想用它來生成一些重複的代碼。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(){} 

}; 

任何想法?

回答

1

模板將顯示您提供給他們的一些數據。所以重要的問題是,該模板將如何知道要輸出的三個三元組:class/attrType/attrName你應該通過它提供的人的名單,讓我們稱之爲props,然後只需用循環

<#list props as prop> 
    ValueProvider<${prop.clazz},${prop.attrType}> ${prop.attrName}(); 
</#list> 

否則創建可重用的小模板,要麼使用#macro(這個人是更靈活)或#include。看到他們在FreeMarker Manual

+0

我將解決方案與列表一起使用。我在數據模型中添加了一個Entry <「props」,List >>,然後我使用了你的模板。它工作很好:) –