Search code examples
freemarker

Freemarker - Check if list contains only empty Strings


I have a list, with possible only empty strings.

My goal is the create a if cause, where I can recognise if the list contains only empty strings.

When I try:

    if list?size gt 0, 

I always get into the if loop, because the list is not empty, it contains empty strings.

Here an example:

All strings can be empty ("").

    <#assign list = [string1, string2, string3, string4, string5]>

    <#if list contains not only empty strings >

    do some things 

    </#if>

Output should be: Only enter the if loop, when list contains not only empty strings.

Does anyone have any idea how this could work? (Without going through the whole list and check each string)


Solution

  • But, you have to go through the whole list, at least as of FreeMarker 2.3.28. Write a function for it:

    <#function containsNonEmpty ls>
      <#list ls as i>
        <#if i != ''>
          <#return true>
        </#if>
      </#list>
      <#return false>
    </#function>
    

    Maybe what you really want is removing the empty elements, even if not all elements are empty. And then check if the list is empty. In 2.3.29 you will be able to use myList?filter(s -> s != '') for that.