Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freemarker iterate ArrayList of Objects and access a variable?

I have the following POJO class:

public final class Item
{
    public final long id;
    public final String hash;

    public Item(long _id, String _hash)
    {
        id = _id;
        hash = _hash;
    }
}

I have an ArrayList<Item>:

ArrayList<Item> list = new ArrayList<>();
list.add(new Item(1, "abc"));
list.add(new Item(2, "def"));

The list is added to the template:

MODEL.addAttribute("history_list", list);

The template successfully iterates through the list the number of times that an item was inserted but fails to get the property of the individual item:

<#list history_list as row>
     <p>${row.hash}</p>
<#else>
     no items here
</#list>

The error: The following has evaluated to null or missing: ==> row.hash [in template "history.ftl" at line 9, column 69]

Why?

like image 248
Gábor DANI Avatar asked Jul 03 '26 20:07

Gábor DANI


1 Answers

There was such a mail list request to allow access to public fields The solution is to use method setExposeFields

DefaultObjectWrapper wrapper = new DefaultObjectWrapper(); 
wrapper.setExposeFields(true); 
FreeMarkerCfg.setObjectWrapper(wrapper); 

This is explained in freemarker docs

If you call setExposeFields(true) on a BeansWrapper instance, it will also expose public, non-static fields of classes as hash keys and values. I.e. if foo is a public, non-static field of the class Bar, and bar is a template variable wrapping an instance of Bar, then bar.foo expression will evaluate as the value of the field foo of the bar object. The public fields in all superclasses of the class are also exposed.

like image 105
user7294900 Avatar answered Jul 06 '26 08:07

user7294900



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!