Sawyer05 Sawyer05 - 1 month ago 12
Twig Question

Using if/else with twig based on viewport size

I'm using twig to create a small responsive website to list out photos from an array over several pages. For the front-end, I'm using bootstrap to list to display them in neat rows for each device.

<div class="row-fluid">
{% for index, photo in photos %}
<div class="col-xs-6 col-sm-4">
{% if (index + 1) % 2 == 0 %}
</div>
<div class="row-fluid">
{% endif %}
{% endfor %}
</div>
</div>


I want this to list out and start a new row if there's 2 on mobile, or 3 in a row on a larger device. My question is based on this line;

{% if (index + 1) % 2 == 0 %}


Based on the screen size, I'd like to be able to change the
2
to be a higher value if the viewport is a certain width to display more products in a row. I can't think of a solution for doing this. I know I could use Ajax to pass the width of the viewport when the screen resizes, but I'm not show how I could set that value to automatically update my twig if statement.

Any help would be greatly appreciated.

Answer

I see that twig has special loop variables that you 'might' be able to use. However, I'm not certain if it will work. Can you try it out:

<div class="row-fluid">
    {% for photo in photos %}
        <div class="col-xs-6 col-sm-4">
        {% if (loop.index + 1) % 2 == 0 %}
            </div>
            <div class="row-fluid">
        {% endif %}
    {% endfor %}     
        </div>
</div>

No guarantee that it will work though - but try it!

Comments