1

I'm looking for shorter way of doing this:

dog dog dog

––––––––––––––––––––––––––

cat cat cat

––––––––––––––––––––––––––

hamster hamster hamster

Currently, I have to run 3 independent loops to group pet types together, and insert a line rule between them.

How can I group pet types together and separate using a line rule?

<div class="row">
      {% for pet in entries %}
            {% if pet.kind == 'dog' %}
                {% include '_partials/animalOrgChart' with {
                  title: pet.title,
                  subTitle: pet.jobTitle,
                  img: pet.headshot|length ? pet.headshot[0],                      
                  url: pet.url,
                  portrait: true
                } %}
            {% endif %}
      {% endfor %}
    <hr class="line" /> 
  </div>
<div class="row">
          {% for pet in entries %}
                {% if pet.kind == 'cat' %}
                    {% include '_partials/animalOrgChart' with {
                      title: pet.title,
                      subTitle: pet.jobTitle,
                      img: pet.headshot|length ? pet.headshot[0],                      
                      url: pet.url,
                      portrait: true
                    } %}
                {% endif %}
          {% endfor %}
        <hr class="line" /> 
   </div>
<div class="row">
          {% for pet in entries %}
                {% if pet.kind == 'hamster' %}
                    {% include '_partials/animalOrgChart' with {
                      title: pet.title,
                      subTitle: pet.jobTitle,
                      img: pet.headshot|length ? pet.headshot[0],                      
                      url: pet.url,
                      portrait: true
                    } %}
                {% endif %}
          {% endfor %}
        <hr class="line" /> 
   </div>

1 Answer 1

3

You can use the group filter

{% set allEntries = craft.entries.section('pets').all() %}
{% set allEntriesByType = allEntries|group('type') %}
{% for type, pets in allEntriesByType %}

     All Pets of Type {{ type }}

     {% for pet in pets %}
         {% include '_partials/animalOrgChart' with {
             title: pet.title,
             subTitle: pet.jobTitle,
             img: pet.headshot|length ? pet.headshot[0],                      
             url: pet.url,
             portrait: true
         } %}        
    {% endfor %}

    <hr class="line" /> 
{% endfor %}
1
  • This is great, so simple and concise. For {% set allEntriesByType = allEntries|group('type') %}, I'm targeting a field handle. It works great @Robin. Thanks again.
    – TRIM
    Commented May 18, 2018 at 13:20

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.