5

我花了一段时间试图在文档中识别这个“特殊变量”。我有一个案例,我希望能够将根哈希传递给可以对其进行操作的宏。我找到了对 Environment.getCurrentEnvironment() 的引用,但这适用于 Java 而不是模板。如何将根数据模型传递给宏?

4

1 回答 1

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; }
}
}
于 2012-05-31T20:36:13.643 回答