One a recent 8.x web project I had to get a menu as a select list to use it on the mobile versions of the website. The menu was 2 level depth but the pattern can be used for every level menus. Each select list options havs a data-url value taken from the menu path so the select list can be used with js to trigger a page redirect on select change event.

So here are the steps to manage it.

1) Create a Menu

2) Add a Menu block. On the block configuration settings on "Theme hook suggestion*" add a new suggestion: menu__jump.

Menu block theme suggestion

3) Create the Twig template menu--jump.html.twig:

{% 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 %}
            <select{{ attributes.addClass('custom-jump-menu') }}>
        {% else %}
            <select class="custom-jump-menu">
        {% endif %}
        {% for item in items %}
            {% set classes = [
            item.in_active_trail ? 'selected',
            ] %}
    <option{{ item.attributes.addClass(classes) }} data-url="{{ item.url }}">{{ item.title }}</option>

{% if item.below %}
    {% for item2 in item.below %}
    <option{{ item2.attributes.addClass(classes) }} data-url="{{ item2.url }}">- {{ item2.title }}</option>
    {% endfor %}
{% endif %}

        {% endfor %}
        </select>
    {% endif %}
{% endmacro %}

Add new comment