1

I only want one block on the home page, other pages can loop through all of them. Is there a more efficient way to write this?

{% if craft.request.getSegment(1) is empty %}
        {% for block in memberships.memberships.limit(1) %}
        <a href="{{ block.urlLocation }}" class="center" target="_blank">
            {% for asset in block.logo %}
                <img src="{{ asset.url('memberships')}}" alt="{{ asset.title }}" />
            {% endfor %}
        </a>
        {% endfor %}
    {% else %}
        {% for block in memberships.memberships %}
        <a href="{{ block.urlLocation }}" class="center" target="_blank">
            {% for asset in block.logo %}
                <img src="{{ asset.url('memberships')}}" alt="{{ asset.title }}" />
            {% endfor %}
        </a>
        {% endfor %}
    {% endif %}
3

You could do it this way:

{% set blockLimit = entry.section.isHomepage() ? 1 : null %}

{% for block in memberships.memberships.limit(blockLimit) %}
  <a href="{{ block.urlLocation }}" class="center" target="_blank">
    {% for asset in block.logo %}
      <img src="{{ asset.url('memberships')}}" alt="{{ asset.title }}" />
    {% endfor %}
  </a>
{% endfor %}

entry.section returns the SectionModel for the entry, and isHomepage() tells you whether that section is the homepage. Then you set your limit accordingly.

  • 1
    Great answer! The only change I'd make is setting limit = (entry.section.isHomepage() ? 1 : null) beforehand (simply for code legibility). It may also be necessary on pages where entry is not defined. – Lindsey D Aug 14 '15 at 19:10
  • freaking sweet! – Mark Busnelli Jr Aug 14 '15 at 20:33
  • 1
    @LindseyD totally right about the code legibility. I will edit my answer – Marion Newlevant Aug 14 '15 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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