This problem took much longer than expected to solve. The goal was to display a menu block where only the children of the active menu link are shown. It turns out to be much simpler than what I had imagined. In Drupal 7, it was achieved by a custom module that loops through each menu item and removes/unsets the inactive items. Here is the solution in Drupal 8:

We had first created a menu template override:

cp core/modules/system/templates/menu.html.twig themes/custom/ourtheme/templates/menu--main--sidebar-left.html.twig

In that template override, I changed the line {% if item.below %} to {% if item.below and item.in_active_trail %} (towards the end of the file):


{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes }}>
    {% else %}
      <ul>
    {% endif %}
    {% for item in items %}
      <li{{ item.attributes }}>
        {{ link(item.title, item.url) }}
        {% if item.below and item.in_active_trail %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Resources