问题描述
因此,在很多地方,即这里:
So, at many places, i.e. here:
https://www .drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links
说明了如何从模块的module_name.links.menu.yml
向现有菜单添加菜单项.
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?
因此,我有一个菜单,我想添加一个菜单项,但是在每种语言上,该菜单项应具有不同的标题和指向的URL.
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.
推荐答案
成功.我创建的第一个links.menu.yml是这样的:
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
然后我像这样将其添加到模块hook_menu_links_discovered_alter()
中:
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:
我没有使用该挂钩函数,而是向links.menu.yml添加了"class"参数:
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
然后,当然,我在my_module/src/Plugin/Menu
中创建了该类(不要忘记将插件放在src dir中!),它看起来像:
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');
}
}
这篇关于Drupal 8:如何从.links.menu.yml创建多语言菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!