简体   繁体   中英

Passing a java list to an html template

I have a printed export from an html file that it takes imports from a Map as shown below

Template t = TemplateLoader.load("Printing/acount.html");
Map<String, Object> map = new HashMap<String, Object>();
map.put("accountName ", e.accountName);
map.put("accountAmount ", acAmount);
    return t.render(map);

And loads the parametres to the html file

<div>
     Account: <font size="3"><b>${ accountName }</b> ${accountAmount}</font> <br/>

And its export looks like

Account 15884 5.000

What if I want to have multiple records in my export?

Lets say

Account 15885 2.000

Account 15886 4.000

Account 15887 3.000

How should be the html and java code in the second case in order to pas an uknown number of records?

If you have List, you can do

map.put("accounts", theAccountList);

In the template (which I assume is FreeMarker) you do:

<#list accounts as account>
 <div>Account: <font size="3"><b>${account.getName()}</b> ${account.getAmount()}</font> <br/></div>
</#list>  

You are now creating a Map with values for accountName and accountAmount . What you should do is add a list of objects that each contain a value for accountName and accountAmount .

It would look something like this:

Map<String, Object> map = new HashMap<String, Object>();
List<Account> accounts = new ArrayList<Account>();
map.put("accounts", accounts);
return t.render(map);

In your template you can then iterate over the items in ${ accounts } (eg, for each account in accounts ) and print each value of account.name and account.amount .

I'm not familiar with the exact syntax of these templates but the approach should be along these lines.

Use a list and a for loop. Look up JSP or JSTL for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM