Freemarker in Liferay List?has_content returns TRUE although list not exist or empty

Viewed 267

Depending on the existence of a list or the fact that this list is not empty I want to have a shown or not. My code:

<#if EventPictures.getSiblings()?has_content> 
    <section class="more grid">
      <#list EventPictures.getSiblings() as cur_EventPictures>
        <#if cur_EventPictures.getData()?? && cur_EventPictures.getData() != "">
    <div class="more-content">
      <div class="strcontainer">
            ... Fill the content
        </div>
    </div>
    
        </#if>
    </#list>
  </section> 
</#if>

Even there is nothing in EventPictures, the section, including the divs, is still shown although there is no content. The Freemarker code is used in Liferay. Why is this not working?

2 Answers

With the input of user7294900 I started realising that Liferay, based on the template always creates the list. If you did not enter anything in the list, It creates an list with 1 item. That item is empty. So list size is always 1 but can be empty. Checking the content of the list items does the job. I added one piece of code with an extra variable to make it happen.

    <#assign EventPicturesCount = "Empty">
    <#if EventPictures.getSiblings()?has_content>
    <#list EventPictures.getSiblings() as cur_EventPictures>
        <#if cur_EventPictures.getData()?? && cur_EventPictures.getData() == "">
        <#else>
            <#assign EventPicturesCount = "Filled">
        </#if>
    </#list>
    
</#if>
<#if EventPicturesCount ?? && EventPicturesCount != "Empty">  

Now the section does only appear when the first listitem has content. I assume it can be shortened but as I am not an experienced user. I will have it this way.

Freemarker's has_content doc suggest using expr!?size > 0 instead

Note that when your data-model implements multiple template model interfaces you may get unexpected results. However, when in doubt you can use always use expr!?size > 0 or expr!?length > 0 instead of expr?has_content

<#if (EventPictures.getSiblings()!?size > 0)>
Related