Stefano php, milano

How to output a grid with Twig and Boostrap

With Twig, the easiest way to format a result-set into a grid is through the batch filter:


{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

{% for row in items|batch(3) %}
<div class="row">
    {% for cell in row %}
        <div class="col-xs-4">{{ cell }}</div>
    {% endfor %}
</div>
{% endfor %}

The example above will output a 3 column grid. Just make sure to adjust your css classes to set the cells' width accordingly.

If you want to output a table instead, you can follow this example from the official documentation:


{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

Here's also a full example of a Bootstrap media grid, plus Laravel pagination:


{% for row in items|batch(2) %}
<div class="row">
    {% for i in row %}
    <div class="media col-xs-6">
        {% if i.photo|trim %}
        <a class="pull-left" href="/post/{{ i.id }}">
            <img class="media-object" src="/uploads/{{ i.filename }}" alt="{{ i.title }}">
        </a>
        {% endif %}
        <div class="media-body">
            <a href="/post/{{ i.id }}">
                <h4 class="media-heading">{{ i.title }}</h4>
            </a>
            <div class="date">{{ i.publication_date|date('M d, Y') }}</div>
            <p>{{ Str_words(i.body|striptags, 20) }}</p>
            <a href="/post/{{ i.id }}" class="read-more">Read more &rarr;</a>
        </div>
    </div>
    {% endfor %}
</div>
{% endfor %}

{{ items.appends(Input_except('page')).links()|raw }}

Enjoy!

Tags: twig, laravel