Hielke
Hielke

Reputation: 189

How to manipulate count based on sub-values in TWIG?

I was wondering how to manipulate / render the count based on sub-rules. In the current situation specifications are counted and when there are more than 5, a link is shown to show more specifications. I wanted to show only specs that have a value like this:

{% for spec in product.specs | limit(5) %}
   {% if spec.value %}
      <li>
         <span>{{ spec.title }}</span>
         {{ spec.value }}
     </li>
   {% endif %}
{% endfor %}
{% if product.specs | length > 5 %}
   <li class="more"><a href="./">{{ 'View all specifications' | t }}</a></li>
{% endif %}

In this case the count is done before checking the values of the sub-items, so the "Show more" link is visible and clickable, but doesn't show more specifications, because they are stripped out, because the value is empty but is counted as item.

The goal is to hide the "Show more" link when there are < 5 items WITH values.

I hope anyone could point me in the right direction :-)

Thank you very much for thinking with me!

Upvotes: 1

Views: 48

Answers (1)

DarkBee
DarkBee

Reputation: 15623

You could either use an extra counter to count the valid elements,

{% for spec in product.specs  | limit(5) %}
   {% if spec.value %}
      <li>
         <span>{{ spec.title }}</span>
         {{ spec.value }}
     </li>
   {% endif %}
{% endfor %}

{% set cnt = 0 %}
{% for spec in product.specs %}
    {% if spec.value %}{% set cnt = cnt + 1 %}{% endif %}
{% endfor %}


{% if cnt >= 5 %}
   <li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}

Or you can use the filter filter

{% if products.specs| filter(spec => spec.value|default) | length >= 5 %}
   <li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}

Update as for your comment (and as you don't have access to filter) You can't just limit the result before hand. So in the first part you would also need to use a counter

{% set cnt = 0 %}
{% for spec in product.specs %}
    {% if cnt < 5 %}
        {% if spec.value %}
        <li>
            <span>{{ spec.title }}</span>
            {{ spec.value }}
        </li>
        {% set cnt = cnt + 1 %}
        {% endif %}
    {% endif %}
{% endfor %}

Upvotes: 1

Related Questions