Search code examples
phphtmltemplate-enginetemplating

Templating: what is the best way to display list of items with separators?


Let's say I have an array of data which I want to display as a list:

$goods = [
    ['title' => 'First item', 'description' => 'First item description'],
    ['title' => 'Second item', 'description' => 'Second item description'],
    ['title' => 'Third item', 'description' => 'Third item description']
];

And the following view:

<div class="good-block">
    <h1>{{ $good['title'] }}</h1>
    <p>{{ $good['description'] }}</p>
</div>

Now I want to display all the items using <hr> as a separator.

Therefore, the final view is as follows:

@foreach ($goods as $good)
    <div class="good-block">
        <h1>{{ $good['title'] }}</h1>
        <p>{{ $good['description'] }}</p>
    </div>
    <hr />
@endforeach

The problem is that, obviously, the separator will be displayed after the last item, not only between the elements. In the case of simple arrays implode can be used as a tool for splicing.

But how to use this approach in the template files? Is there a different approach, allowing to keep the code clean and logical, without adding unnecessary conditions like checking the current element is not last element of an array?

Thanks!


Solution

  • A simple trick is to keep a $counter, like so:

    @$counter = 0;
    @foreach ($goods as $good)
        @if ( $counter > 0 ) print '<hr />';
        <div class="good-block">
            <h1>{{ $good['title'] }}</h1>
            <p>{{ $good['description'] }}</p>
        </div>
        @$counter++
    @endforeach
    

    Now your hr will only appear before your entry, but it skips the first one.