问题
So, at many places, i.e. here:
https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links
It's explained how to add menu item to some existing menu from module_name.links.menu.yml
of your module.
Problem is that menu items can be translatable (from back-end), but I didn't find anywhere how to add menu items in multiple languages? Is that possible at all?
So, I have one menu, I want to add one menu item, but on each language that menu item should have different title and different url where it leads to.
回答1:
Succeeded. First links.menu.yml I created like this:
my_menu_item_id:
title: 'Dummy Title'
description: 'Dummy Description'
url: http://www.google.com
parent: mainmenu
menu_name: mainmenu
weight: -100
Then I added to my module hook_menu_links_discovered_alter()
like this:
function mymodule_menu_links_discovered_alter(&$links) {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$links['my_menu_item_id']['title'] = 'Title:'.$language;
}
And basically that works, but problem is that it's not executed with every request, but it's cached. So i.e. if you want to have different title or url depending on language it won't work. Version for first language will be cached and for all other languages same cached version will be used. So I had to go for different solution:
Instead of using that hook function I added "class" parameter to links.menu.yml:
my_menu_item_id:
class: Drupal\my_module\Plugin\Menu\MyPluginClass
title: 'Dummy Title'
description: 'Dummy Description'
url: http://www.google.com
parent: mainmenu
menu_name: mainmenu
weight: -100
Then of course, I created that class in my_module/src/Plugin/Menu
(don't forget to put plugin inside src dir!) and it looks like:
<?php
namespace Drupal\my_module\Plugin\Menu;
use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;
class MyPluginClass extends MenuLinkDefault {
/**
* {@inheritdoc}
*/
public function getTitle() {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
return (string) 'Title: '.$language;
}
public function getUrlObject($title_attribute = TRUE) {
return Url::fromUri('http://www.yahoo.com');
}
}
来源:https://stackoverflow.com/questions/52254659/drupal-8-how-to-create-multi-lingual-menu-item-from-links-menu-yml