gist JS

Thursday, November 08, 2007

Using Maps of objects in Freemarker

Because sometimes helpful, well-written FAQ's that address precisely your problem are no substitute for an example, I present you with:

Using Maps of objects in Freemarker, the missing example for:

Why I can't use non-string key in the myMap[myKey] expression? And what to do now?

Here's our class and its HashMap and regular getter:

public class Application implements Serializable {
private <ProcessType, ProcessValue> process = new HashMap<ProcessType,ProcessValue>();

public Map<ProcessType, ProcessValue> getProcess() {
return process;

We can't use this getter because it's wrapped by the Freemarker BeanModel and only accepts Strings.

Here's the new getter that we'll add:

    public ProcessValue getTheProcess(ProcessType type) {
return getProcess().get(type);

And then in our Freemarker template, we call the new getter method.

<#list application.process?keys as processType>

OMG there's a new Neal Stephenson book.


Anonymous said...

Thanks! :) That was very helpful for me.

Unknown said...

Thx. I was looking for a clean solution for this problem.

Anonymous said...

Thanks, Jeff!
Your post really helps me.


Mark Nenadov said...

by the way that link to the FAQ is broken now... its now item #14.

jspringbernate said...

the first line should be

private Map process = new HashMap();

Map is missing

Anonymous said...

Thanks, that really helped me out. One example really is worth a thousand words of incomprehensible FAQ.