Let's say in my index page I would like to display all of my categories, their subcategories and the number of products each category has.
When I have a lot of objects the query count becomes huge. I already reduced the count by triple by using Querybuilder to fetch all the categories. However, there are stil alot of queries, when I am displaying everything in twig.
{% for category in categories %}
{% if app.request.getLocale() == 'en' %}
<li class="subMenu" style="cursor:pointer;"><a> {{ category.name }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: subcategory.name}) }}">{{ subcategory.name }} [{{ countSubProducts(subcategory.id)}}]</a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: category.name}) }}">{{ "category.show_all" | trans }} [{{ countCatProducts(category.id)}}]</a></li>
</ul>
</li>
{% else %}
<li class="subMenu" style="cursor:pointer;"><a> {{ category.nameEs }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: subcategory.nameEs}) }}">{{ subcategory.getNameEs }} [{{ countCatProducts(subcategory.id)}}] </a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: category.nameEs}) }}">{{ "category.show_all" | trans }} [{{ countSubProducts(category.id)}}]</a></li>
</ul>
</li>
{% endif %}
{% endfor %}
As you can see, I am doing allot of for loops, because I dont know any other way to display each category/subategory.
These loops are making allot of queries... How can I reduce all this? Is it possible?
You can do something like this :
Use of twig attribute
{% set myname = "nameEs" %}
{% if app.request.getLocale() == 'en' %}
{% set myname = "name" %}
{% endif %}
{% for category in categories %}
<li class="subMenu" style="cursor:pointer;"><a> {{ attribute(category, myname) }}</a>
<ul>
{% for subcategory in category.children %}
<li><a href="{{ path('products_in_categories', {id: subcategory.id, name: attribute(subcategory, myname)}) }}">{{ attribute(subcategory, myname) }} [{{ countSubProducts(subcategory.id)}}]</a></li>
{% endfor %}
<li><a href="{{ path('products_in_categories', {id: category.id, name: attribute(category, myname)}) }}">{{ "category.show_all" | trans }} [{{ countCatProducts(category.id)}}]</a></li>
</ul>
</li>
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.