2012-05-31 50 views
5

我花了一段時間試圖在文檔中識別這個'特殊變量'。我有一個情況,我希望能夠將根哈希傳遞給一個可以對其進行操作的宏。我找到了Environment.getCurrentEnvironment()的引用,但是它在Java中不起作用。如何將根數據模型傳遞給宏?如何訪問我的FreeMarker模板中的根bean?

回答

5

下面是一個單元測試,成功完成了我之後的工作。關鍵是'.data_model'變量。

public class TestFreeMarkerTemplating { 

Configuration cfg = new Configuration(); 
StringTemplateLoader stringLoader = new StringTemplateLoader(); 
{ cfg.setTemplateLoader(stringLoader); 
cfg.setObjectWrapper(new BeansWrapper()); } 

@Test 
public void testTestableMacros() throws TemplateException, IOException{ 
    stringLoader.putTemplate("root", "<#macro user testPojo>Welcome ${testPojo.user}. <@subPojo sub/></#macro><#macro subPojo sub>Sub ${sub.user}!</#macro>"); 
    stringLoader.putTemplate("testPojoTemplate", "<#import \"root\" as w><@w.user .data_model/>"); 
    stringLoader.putTemplate("testSubPojoTemplate", "<#import \"root\" as w><@w.subPojo .data_model/>"); 
    assertTemplateAndBeanYield("root", new TestPojo(), ""); 
    assertTemplateAndBeanYield("testPojoTemplate", new TestPojo(), "Welcome Andy. Sub Bill!"); 
    assertTemplateAndBeanYield("testSubPojoTemplate", new SubPojo(), "Sub Bill!"); 

} 

public void assertTemplateAndBeanYield(String templateName, Object bean, String expectedOutput) throws IOException, TemplateException{ 
    Template temp = cfg.getTemplate(templateName); 
    StringWriter out = new StringWriter(); 
    temp.process(bean, out); 

    assertEquals(expectedOutput, out.toString()); 
} 

public static class TestPojo { 
    private final String user = "Andy"; 
    private final SubPojo sub = new SubPojo(); 

    public String getUser() { return user; } 
    public SubPojo getSub() { return sub; } 
} 

public static class SubPojo { 
    private final String user = "Bill"; 

    public String getUser() { return user; } 
} 
}