Himanshu Yadav
Himanshu Yadav

Reputation: 13585

Freemarker: Advanced use of for loop

It is an extension of my previous question. Now I can divide list of elements in chunk of 2 and place both elements into two columns of a single row.
Freemarker code

<#list section.field?chunk(2) as row>
    <div class="row field">
      <#list row as field>
        <@customFields.createField field=field/>
      </#list>
    </div>
</#list>

Generated HTML Code:

<div class="row field">
  <div class="col-xs-6 col-sm-6 col-md-6"><!-- column 1-->
       <label class="pocLabel">Received Date</label>
       <input type="text" name="Date" class="datePicker" required=""/>
  </div>
  <div class="col-xs-6 col-sm-6 col-md-6"> <!-- column 2-->
       <label class="pocLabel">Signed Date</label>
       <input type="text" name="Date" class="datePicker" />
  </div>
</div>

But what happens when I come across a field which has to be place on row level. It will be in a row with no columns.
Expected Freemarker code (pseudo code) :

<#if field.@type='rowLevel'>

<#else>
<div class="row field">
          <#list row as field>
            <@customFields.createField field=field/>
          </#list>
        </div>
</#if>

Expected HTML Code for row level field:

<div class="row field">
 <label class="pocLabel">Signed Date</label>
 <input type="text" name="SignedDate" class="datePicker"/>
</div>

Upvotes: 0

Views: 816

Answers (1)

ddekany
ddekany

Reputation: 31152

Since ?chunk can't detect the width of the cells (if it's 1 or 2), you will have to work out the algorithm yourself. As it's easier to write than read, I recommend putting it into a macro, and then call the macro. The basic algorithm (or a possible variation of it) is like:

<#-- Prints the fields arranged to two columns: -->
<#macro columnate fileds>
  <#local inCol1 = true>
  <#list fields as field>
    <#local fullRow = isFullRow(field)>

    <#if inCol1 || fullRow>
      <div class="row field"> <!-- row starts --->
    </#if>

    <#if !fullRow>
      <div class="col-xs-6 col-sm-6 col-md-6"> <!-- column ${inCol1?string('1', '2')} -->
    </#if>
    <@customFields.createField field=field />
    <#if !fullRow>
      </div>
    </#if>

    <#if !inCol1 || fullRow || !field_has_next || isFullRow(fields[field_index + 1])>
      </div> <!-- row ends -->
    </#if>

    <#local inCol1 = !inCol1 || fullRow>
  </#list>
</#macro>

<#function isFullRow field>
  <#return field.@type == 'rowLevel'>
</#function>

You probably want to put it into an #include-d/#import-ed file for reuse. And now, whereever you need this, you can just do this:

<@columnate fields />

Upvotes: 1

Related Questions