twig macro code example

Example 1: import macros twig

{% import "forms.html" as forms %}

Example 2: menu macro twig example

{% macro menuMacro(menu, level) -%}

  {# Set our default level as an integer. #}
  {% set default_level = 1 %}

  <ul class=”menu-level--{{ level|default(default_level) }}”>
    {% for menu_item in menu %}
      {# Check if this is the active item. #}
      {% set active = (menu_item.active) ? ' is-active' : '' %}

      {# Check if this item is in the active trail. #}
      {% set active = active ~ ((menu_item.active_trail) ? ' is-active-trail' : '') %}

      <li class=”menu__item{{ active }}”>
        <a href="{{ menu_item.url }}"  class=”menu__link{{ active }}”>{{ menu_item.text }}</a>
        {% if menu_item.submenu %}
            {# Since this menu item has a submenu, recall function and increment counter. #}
          {{ _self.menuMacro(menu_item.submenu, level|default(default_level) + 1) }}
        {% endif %}
      </li>
    {% endfor %}
  </ul>
{%- endmacro %}

Tags:

Misc Example