Search code examples
freemarker

How to write a clean code with free-marker template in multiple if and else blocks?


I am new to free-marker template and in my template its seems that I might have to repeat a lot of if and else blocks with repetition of same if condition. Is there a more convenient or cleaner way of writing this if block or instead of repeating them.

               <span > </span>
         <#elseif section.role?has_content && section.person?has_content && section.organisation??>
           <span > </span>
         <#elseif section.role?has_content && section.organisation?has_content && section.person??>
           <span > </span>
         <#elseif section.person?has_content && section.organisation?has_content && section.role??>
               <span > </span>
         <#elseif section.person?has_content && section.role?? && section.organisation??>
               <span > </span>
         <#elseif section.organisation?has_content && section.role?? && section.person??>
               <span > </span>
         <#elseif section.role?has_content && section.organisation?? && section.person??>
               <span > </span>
         </#if>

Solution

    • I think you can do something like this in freemaker which is much cleaner then repeating the conditions.

    • Instead of repeating this section.role?has_content multiple times you can assign this condition value in a variable and use it later like this <#assign hasRole = section.role?has_content />

               <#assign hasRole = section.role?has_content />
               <#assign hasOrganisation = section.organisation?has_content />
    
               <span >
                    <#if section.person?has_content><span ></span><#if section.role?has_content><span ></span></#if></#if>
                    <#if section.role?has_content><span ></span><#if section.organisation?has_content><span ></span></#if></#if>
                    <#if section.organisation?has_content>
                        <span ></span>
    
                    </#if>
               </span>```