How to check for null List in freemarker

Kraken picture Kraken · Sep 24, 2012 · Viewed 44.5k times · Source

Say my java code has List<String> listS =null and i pass this to my template file.

Now i want to make sure that if list has some data then only do something.

I have tried

<#if listS = null>
AND
<#if !listS>
AND
<#if listS?size=0>

But none of these seem to be working. I have some logic i my java code ; through which , if some condition is true, then i new this listS and populate it.

Hence i need to know if the listS has been populated or is null only, in my template file.

How do i do this? Thanks.

EDIT: Also, i have a list of Structures, each containing this listS,(populated or not is a different issue), and i am passing the entire list of structure, hence passing a boolean value to the template file along with my list of Structures is not possible, since i will have to traverse within each list, and that traversal I want to do in the template file itself.

EDIT 2: For those who know what's Java null, FreeMarker 2.3.x treats them as missing values. Simply, the template language doesn't know the concept of null. For example, if you have a bean that has a maidenName property, and the value of that property is null, then that's the same as if there were no such property at all, as far as the template is concerned (assuming you didn't configured FreeMarker to use some extreme object wrapper, that is). The result of a method call that returns null is also treated as a missing variable (again, assuming that you use some usual object wrapper). See more in the FAQ.

Freemarker Manual

But I still havent got the answer for how to make it work, if at all I can.

Answer

Bohemian picture Bohemian · Sep 24, 2012

Use the has_content built-in:

<#if list5?has_content>