Sensiolabs Insight: Twig Templates Should Not Contain Business Logic
I am actually analyzing Sensiolabs Insight analysis on my Symfony 2.8 project.
I have a basic problem with some of my Twig templates:
Twig templates should not contain business logic
The associated message is always the same:
The pattern is too complex, depth 10 has been reached, but only 5 is allowed.
For example, this happens with the following pattern:
{% extends "FBNGuideBundle::layout.html.twig" %} {% block title %} {{ 'fbn.guide.page_title.bookmarks'|trans }} {% endblock %} {% block body %} <div id="bookmarks" data-bookmark-ids="{{bookmarkIds|json_encode()}}"> {% if (restaurants|length > 0) %} <div class="restaurants"> <h3>MES RESTOS</h3> {% for bookmark in restaurants %} <div class="bookmark" id="{{'bookmark-' ~ bookmark.id}}"> <a href="{{ path('fbn_guide_restaurants', {'slug': bookmark.restaurant.slug} ) }}">{{ bookmark.restaurant.name }}</a> <br> <br> <button>SUPPRIMER DES FAVORIS</button> <br> <hr> </div> {% endfor %} </div> {% endif %} </div> {% endblock %}
I tried to include in a separate file the code contained inside <div id="bookmarks"></div>
and the depth was reduced, but this is not a solution. I guess the problem is accessing some properties across multiple objects using getters (ie bookmark.restaurant.slug)
.
I have a free plan, so I cannot access the documentation associated with this warning. Does anyone know how to fix the problem?
Thank.
source to share
When you have too much logic in the view, you can put it in a custom Twig extension. The advantage is that you don't need to duplicate the html if you reuse that part on another page, and of course the code is clearer :) In your case, you can write a new Twig extension that displays all the bookmarks.
If you haven't created something like this so far, you can read about it here http://symfony.com/doc/current/templating/twig_extension.html
source to share