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 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合