Score:0

Hash in menu item url are removed when displaying the menu on a page

gb flag

If a menu item has a submenu and I specify the hash symbol (#) in the Link field of such parent menu item in the admin panel, I receive empty url at the frontend and therefore if click by such link, I follow to the homepage.

Even if I use in my menu--main.html.twig template the code like

{% set menu_item_url = item.url %}
{% if menu_item_url == '' %}
{% set menu_item_url = '#' %}
{% endif %}
<a href="{{ menu_item_url }}" ...

I still receive empty href=""

How to resolve the problem? I mean is there a way inside of templates? Of course, I know that I can resolve the problem with JS.

Note: I don't mean an anchor, I just need # as parent item url if the item has a submenu.

leymannx avatar
ne flag
What exactly did you enter as link? `/#some-id`?
leymannx avatar
ne flag
Does this answer your question? [How can I have links to anchors in menus?](https://drupal.stackexchange.com/questions/237541/how-can-i-have-links-to-anchors-in-menus)
stckvrw avatar
gb flag
No, I don't mean an anchor. I just need # as parent item url if the item has a submenu
leymannx avatar
ne flag
I don't understand. You want `<a href="#">`? You know you can enter `<nolink>` in the menu UI if the menu item shouldn't be a link?
leymannx avatar
ne flag
Maybe look at [Non-Clickable Menu Items](https://drupal.stackexchange.com/q/229376/15055).
stckvrw avatar
gb flag
@leymannx yes, I want `<a href="#">`. If I enter `<nolink>` or `route:<nolink>` I still receive empty `href=""` at the frontend
leymannx avatar
ne flag
I guess `item.url` is actually an object. Try Twig Debug and then put `{{ dd(item.url) }}`. You maybe want `item.url.value` or similar.
Score:0
uz flag

Here is an example, where clicking 'Example menulink' will not send you elsewhere is you have a submenu item. Otherwise use url: 'internal:##'

MYMODULE.menuitemxyz:
  title: 'Example menulink'
  url: 'internal:#'
  menu_name: mycustom-menu
  weight: 1009
  enabled: 1
  expanded: 1

MYMODULE.menuitesub1:
  title: 'Anchor link'
  parent: MYMODULE.menuitemxyz
  menu_name: mycustom-menu
  url: 'internal:#using_anchors'
  weight: 1007
Score:-1
pl flag

If you do not want a link in the parent menu item, you may also use <none> as link. I always use it for menu items without a link.

leymannx avatar
ne flag
No that's not what they want. See the comments.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.