How to dynamically divide a list in two columns

**Silverstripe Version: 5.5

How can I dynamically divide a list in two columns. So far I had a hard-coded number in MultipleOf(8), but now I want it to be dynamic like <% if MultipleOf($HalfNumberOfItems) %>

My attempt was the following:

in Controller:
public function HalfNumberOfItems(){
        $numberOfItems = Items::get()->filter(['ItemGroup' => 'myitem'])->count();
        return  round($numberOfItems / 2)
    }

in Template
...
<% if MultipleOf($HalfNumberOfItems) %>
    </ul>
    </div>
    <div class="items">
        <ul>
<% end_if %>
...

but that unfortunately doesn’t work.

Can anyone please point me in the right direction?

Thank you.

Untested:

<% if $Pos == $HalfNumberOfItems %>
    </ul>
    </div>
    <div class="items">
        <ul>
<% end_if %>

Thanks for your reply, ntd.
Unfortunately this doesn’t work either.

Any other idea?

Assuming

<% if $Pos == $HalfNumberOfItems %>

is within the scope of a List, then try $Up.HalfNumberOfItems or $Top.HalfNumberOfItems as that method is on the Controller.

eg. Using ntd’s example:

<% loop $MyList %>
  <% if $Pos == $HalfNumberOfItems %>
      </ul>
      </div>
      <div class="items">
          <ul>
  <% end_if %>
<% end_loop %>

Another potential option is looking into GroupedList where you could potentially define a custom method on your DataObject to determine it’s position (although that will probably only be useful if you are just getting all items in your original list).

If all else fails, perhaps two methods? One getting half the list, and another in reverse?

I suppose the question here is why? Is this just for presentation? If so, you can just use CSS columns to deal with the layout - that way the semantic structure of your page will also be retained.

1 Like

Thanks Tim, that was a great idea :grinning:. Sometimes the solution is so simple :wink:.
Thanks again.

1 Like