Below is just ONE possible way to tidy-up / DRY-up the template pair.
The idea is to move the recursion into a macro, so everything lives in a single file (still perfectly cache-able by Twig) while keeping the public entry-point ultra-small.
@AutoAdminMenu/menu.html.twig
{# ---------------------------------------------------------
Public entry-point. Only one responsibility:
call the macro with the root menu collection.
--------------------------------------------------------- #}
{% import _self as m %}
<nav class="navbar navbar-expand-lg">
<ul class="navbar-nav">
{{ m.items(menu.children) }}
</ul>
</nav>
{# =========================================================
MACRO SECTION (recursion happens here)
========================================================= #}
{% macro items(items) %}
{% for item in items if item.display %}
{# --- Assemble <li> classes ------------------------------------ #}
{% set liClasses = ['nav-item'] %}
{% if item.children|length %}
{% set liClasses = liClasses|merge(['dropdown']) %}
{% endif %}
<li class="{{ liClasses|join(' ') }}">
{# --- Render the clickable part (anchor OR span) ------------- #}
{% if item.uri %}
<a class="nav-link{{ item.children ? ' dropdown-toggle' }}"
href="{{ item.uri }}"
{% if item.children %}data-bs-toggle="dropdown" role="button" aria-expanded="false"{% endif %}
>
{{ item.label }}
</a>
{% else %}
<span class="{{ item.children ? 'nav-link dropdown-toggle' : 'nav-text' }}">
{{ item.label }}
</span>
{% endif %}
{# --- Children (recursive) ---------------------------------- #}
{% if item.children|length %}
<ul class="dropdown-menu">
{{ _self.items(item.children) }}
</ul>
{% endif %}
</li>
{% endfor %}
{% endmacro %}
What changed & why?
- Only one template instead of two – less include overhead, easier to reason about.
- All conditional class building is done once via
liClasses / dropdown-toggle helpers → no duplication.
- Recursion is handled inside the macro
_self.items, which keeps the call-site super slim and avoids include inside loops.
- Added a couple of ARIA / data attributes for Bootstrap 5+ friendliness (drop them if you don’t need them).
- The
if item.display filter is placed directly in the for tag for extra clarity.
Feel free to split the macro section into its own partial (e.g. _menu_macros.html.twig) if you prefer, then just change the import line:
{% import '@AutoAdminMenu/_menu_macros.html.twig' as m %}
Happy templating 🎉