Passing a List of Objects to Freemarker and then Looping

坚强是说给别人听的谎言 提交于 2019-12-03 04:16:09

Is "jobs" really a collection? Please post a snippet of code where you are creating and processing your template.

I just wrote a quick test to check:

public void testFreeMarker() throws Exception {

    List<Invoice> invoices = Arrays.asList(
       new Invoice( "note1", "amount1" ), 
       new Invoice( "note2", "amount2" ) );
    Map<String, Object> root = new HashMap<String, Object>();
    root.put( "invoices", invoices );
    StringWriter out = new StringWriter();

    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading( FreemarkerUtils.class, "/templates" );
    cfg.setObjectWrapper( new DefaultObjectWrapper() );
    Template temp = cfg.getTemplate( "listTest.ftl" );
    temp.process( root, out );

    System.out.println( out.getBuffer().toString() );
}

The template is just:

<#list invoices as invoice>
 Item: ${invoice.note} - ${invoice.amount}
</#list>

The result is as expected:

Item: note1 - amount1
Item: note2 - amount2

Both a follow-up question and a possibly off-topic answer..

The question: How do you make your invoice list available to the freemarker template? Could you post the code snippet where you add it to the request / session / whatever?

The possibly off-topic answer: Have you considered using Spring MVC? Imho it makes working with Freemarker as a web page templating mechanism somewhat easier. It provides a FreemarkerViewRenderer and you can just return a "ModelAndView" from your web controller methods... you might want to have a look at it.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-velocity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!