2

I'm using Matrix fields for blog posts. These are made up of text and image block types. I want to pull in only the first image block and a snippet of text from the first text block into the blogs index page for listing the entries.

Adding limit(1) to each block type didn't work.

{% for entry in craft.entries.section('blog').limit(3).find() %}
<div class="col-8  {% if loop.last %}last{% endif %}">

    {% for block in entry.blogBody %}

    {% switch block.type %}

      {% case "text" %}
      {{ block.text|hacksaw(chars='100', append='...') }}

      {% case "blogimage" %}
       {% for asset in block.image %}
          <img src="{{ asset.getUrl() }}" alt=""/>
      {% endfor %}

 {% endswitch %}

{% endfor %}
</div>
{% endfor %}

</div>

{% endblock %}

1 Answer 1

4

You can limit which blocks you want by type and only show the first of each, if they exist. Something like this might do the trick:

{% for entry in craft.entries.section('blog').limit(3).find() %}
    <div class="col-8  {% if loop.last %}last{% endif %}">

        {% set textBlock = entry.blogBody.type('text').first() %}
        {% set imgBlock = entry.blogBody.type('blogimage').first() %}

        {% if textBlock %}
            {{ textBlock.text|hacksaw(chars='100', append='...') }}
        {% endif %}

        {% if imgBlock %}
              <img src="{{ imgBlock.image[0].getUrl() }}" alt=""/>
        {% endif %}
    </div>
{% endfor %}

</div>

{% endblock %}
2
  • Thanks for the reply. I get a Recoverable error : Object of class Craft\ElementCriteriaModel could not be converted to string error for this
    – sarah3585
    Oct 25, 2015 at 8:27
  • @sarah3585 just made an edit - forgot to add .text to your textBlock matrix block. I also changed .limit(1) to .first(). Let me know if that works! Oct 25, 2015 at 16:24

Your Answer

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

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