3

Here's an example, I have three columns in a table: ClassQuarter, Course No, Description.

I would like to output rows only with ClassQuarter == '1' in a HTML table, then output rows where ClassQuarter == '2' in another table, then output rows where ClassQuarter == '3' in another table.

Am I able to output rows with a condition for the first column?

1 Answer 1

2

Since there are a set number of quarters you can probably just collect the entries in a temporary array. Then use those to build your tables.

{% set quarter1 = [] %}
{% set quarter2 = [] %}
{% set quarter3 = [] %}

{% for row in entry.courses %}

    {% if row.classQuarter == 1 %}
        {% set quarter1 = quarter1|merge([row]) %}
    {% endif %}

    {% if row.classQuarter == 2 %}
        {% set quarter2 = quarter2|merge([row]) %}
    {% endif %}

    {% if row.classQuarter == 3 %}
        {% set quarter3 = quarter3|merge([row]) %}
    {% endif %}

{% endfor %}

<table>
    {% for row in quarter1 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr>    
    {% endfor %}
</table>

<table>
    {% for row in quarter2 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr>    
    {% endfor %}
</table>

<table>
    {% for row in quarter3 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr>    
    {% endfor %}
</table>

You could also add an 'if' clause in the 'for...in' loop. See the twig docs on adding a condition for more info.

<table>
    {% for row in entry.courses if row.classQuarter == 1 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr> 
    {% endfor %}
</table>
<table>
    {% for row in entry.courses if row.classQuarter == 2 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr> 
    {% endfor %}
</table>
<table>
    {% for row in entry.courses if row.classQuarter == 3 %}
        <tr>
            <td>{{ row.courseNumber }}</td>
            <td>{{ row.courseDescription }}</td>
        </tr> 
    {% endfor %}
</table>

And could also probably condense that using the range shortcut.

{% for quarter in 1..4 %}
    <table>
        {% for row in entry.courses if row.classQuarter == quarter %}
            <tr>
                <td>{{ row.courseNumber }}</td>
                <td>{{ row.courseDescription }}</td>
            </tr> 
        {% endfor %}
    </table>
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.