2

I've got a Matrix block in my Latest News/Index template and I can't figure out how to only output the first instance of a block type field. Here is my code, working great except it outputs the first 250 characters from ALL {{block.newsContent}} content block fields not just the first. I know this is what my code is actually set up to do, but I can't figure out how to only output the first one!

{% for block in entry.newsBlock %}
    {% switch block.type %}

        {% case 'nbTitle' %}

            <a href="{{ entry.url }}"> <h2> {{ block.newsTitle }} </h2></a>

            <h3>{{ entry.postDate | date("d-M-Y") }}</h3>


        {% case 'nbContent' %}

            <div class="news-content-index">
                <p>{{ block.newsContent | striptags | slice(0, 250) ~ '...' }}</p>
            </div>

    {% endswitch %}
{% endfor %}

The {{block.newsContent}} part outputs every instance of that field, but I only need the first, as it's the 'excerpt' intro to the complete article.

Here is the front end: https://www.ancamotion.com/latest-news

Any help appreciated, thanks!

2

You can either use external bool variable

{% set firstNbContentDisplayed = false %}
{% for block in entry.newsBlock %}
    {% switch block.type %}
        {% case 'nbTitle' %}
            ...
        {% case 'nbContent' %}
            {% if not firstNbContentDisplayed %} 
                {% set firstNbContentDisplayed = true %}
                ...
            {% endif %}
    {% endswitch %}
{% endfor %}

or if possible in your case separate nbContent and limit it to 1

{% for block in entry.newsBlock %}
    {% switch block.type %}
        {% case 'nbTitle' %}
            ...
    {% endswitch %}
{% endfor %}

{% for block in entry.newsBlock.type('nbContent').limit(1) %}
    ...
{% endfor %}
  • Thanks! I ended up using your second option, and it worked. Thank you!!! – Ivy Jul 11 '17 at 0:48
2

I haven't tested this, but I think

{% for block in entry.newsBlock.type('blockType').limit(1) %}
    {{ block.title }}
{% endfor %} 

ought to do it?

If not you could simply do what you're currently doing but also use a

{% if loop.first %}
...
{% endif %}

inside it to only spit out content from the first loop iteration.

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.