0

I want to print categories on top of my loop results. I'm using twig, but categories which I want to print are displaying every time beside iterations. I want to do it that way in order to spare some SQL request.

   {% for goodies in goodies %}                        
   {% if menus.bonbons == 'guimauve'%}
       <div class="col-lg-3">Title</div>
   {% endif %}
       <div class="col-lg-3">{{ iterations }}</div>}

   {% endif %}
   {% endfor %} 

Actually (logically) results are looking like this:

TITLE 
iteration
TITLE 
iteration
TITLE 
iteration
TITLE 
iteration
TITLE 
iteration
TITLE 
iteration

The result I want:

                         TITLE 
iteration
iteration
iteration
iteration
iteration
iteration
iteration

Note that I won't place title before loop because I only want those title for existing categories.

7
  • In fact, there should be only one TITLE iteration because of {% if loop.first %} Commented Oct 16, 2019 at 13:16
  • Note that 'guimove' is actually spelled 'guimauve' Commented Oct 16, 2019 at 13:17
  • Hello Cid, thanks for your support. Commented Oct 16, 2019 at 13:21
  • I cant use first because i have many categories ... Commented Oct 16, 2019 at 13:22
  • If only i could use 'if goodies.categorie in goodies' Commented Oct 16, 2019 at 13:23

1 Answer 1

2

I finaly found a solution,

{% for goodies in goodies|filter(goodies => goodies.typeproduct == 'guimauve') -%}


    {% if loop.first %}
        <div class="col-lg-3  text-center mb-2">Title-Guimauve</div>
    {% endif %}

    {% if not loop.last %}
        <div class="col-lg-3 text-center">{{menus.goodiesname}}</div>
        <div class="col-lg-3 text-center">or</div>
    {% else %}
        <div class="col-lg-3 text-center">{{menus.goodiesname}}</div>
    {% endif %}

    {% endif %}
{% endfor %} 

i invite you to go there if you want some more details about |filter https://twig.symfony.com/doc/2.x/filters/filter.html

I hope it will help some of you !

Sign up to request clarification or add additional context in comments.

1 Comment

Going by the output in your original example, I think the solution can simply be an if statement outside of a loop. If the iterable has items, then print the header, then print the iterable's items. With that you only print the header if the iterable is worth printing and you only print it once.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.