douyu3145 2019-02-27 22:27
浏览 116
已采纳

如何在Drupal 8中将自定义类设置为子菜单?

I am working on sidebar menu in a Custom Drupal 8 Theme. I am trying to set a class of sidebar__menu--submenu-1,sidebar__menu--submenu-2, sidebar__menu--submenu-3 and so on depending on the level of the submenus.

So far, I was able to add the class sidebar__menu to the first level & sidebar__menu--submenu to all the submenus. However, I want to add the class sidebar__menu--submenu-(number of the level) so I can style & control the sidebar better on css.

Here it is my code menu.html.twig:

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level, menu_name) %}
  {% import _self as menus %}
  {%
    set menu_classes = [
      'sidebar__menu' ~ menu_name|clean_class,
    ]
  %}
  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
    ]
  %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('container mx-auto', menu_classes) }}>
    {% else %}
      <ul {{ attributes.removeClass(menu_classes).addClass(submenu_classes) }}>
    {% endif %}

    {% for item in items %}
     {%
      set classes = [
        'sidebar__item',
        item.is_expanded ? 'sidebar__item--expanded',
        item.is_collapsed ? 'sidebar__item--collapsed',
        item.in_active_trail ? 'sidebar__item--active-trail',
      ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Any help will be really appreciate it!

  • 写回答

1条回答 默认 最新

  • doukun5339 2019-02-28 16:01
    关注

    I have found the answer. First we set the classes:

    {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
      'sidebar__menu--submenu-' ~ (menu_level + 1),
    ]
    

    %}

    Then using the logic like so:

    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('container mx-auto', menu_classes) }}>
    {% else %}
      <ul{{ attributes.removeClass(menu_classes, 'sidebar__menu--submenu-' ~ (menu_level)).addClass(submenu_classes) }}>
    {% endif %}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀