Drupal模块开发 - Drupal8 自定义Local Tasks菜单API

翻译者:长风Drupal开发:Drupal8 Local Tasks菜单

原文链接:https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-local-tasks

 

Drupal开发中,Local Tasks菜单通常用于在页面顶部的tabs标签。这通常被用于管理页面,而在前端的用户页面、注册、找回密码也有Local Tasks菜单。

在Drupal8中,Local Tasks菜单在YAML文件中被定义。 

定义静态的Local Tasks菜单

大多数你需要定义的local tasks都是静态的,因此只需要在一个通过你的模块名字命名的文件中就可以定义,比如,如果模块名字是 example,文件名字应该是example.links.task.yml,并且把他放在Drupal8模块中的根目录下,

example.admin: # The first plugin ID
route_name: example.admin  
title: 'Settings'
base_route: example.admin
example.admin_3rd_party: # The second plugin ID
route_name: example.admin_3rd_party
title: 'Third party services'
base_route: example.admin
weight: 100

这个文件定义了两个tabs标签,一个是针对example.admin,另一个是针对example.admin_3rd_party,tab菜单的标题将被显示在用户界面上,tab菜单的base_route和default使用相同的名字。

Drupal8 tab菜单中的base_route 被用于把相关的tab菜单分到一组。

在Drupal8 tab菜单中,你也可以使用weight关键词,用于对Drupal8 tab菜单中的每个子菜单排序。要提供多层的Drupal8 tab菜单,使用parent_id来关联tab菜单和他的父菜单,同样使用base_route连来关联同级别的Drupal8 tab菜单。

学习Drupal8 tab菜单的例子,可以查看在block_content模块中定义的Drupal8 tab菜单

entity.block_content.collection: # (1) Non-default tab by side of "Block layout" (which is on block.admin_display)
title: 'Custom block library'
route_name: entity.block_content.collection
base_route: block.admin_display
block_content.list_sub: # (2) Default subtab, same route as the parent tab, so different tab ID. 
title: Blocks
route_name: entity.block_content.collection
parent_id: entity.block_content.collection
entity.block_content_type.collection: # (3) Non-default subtab alongside the "Blocks" default tab
title: Block types
route_name: entity.block_content_type.collection
parent_id: entity.block_content.collection
weight: 1

entity.block_content_type.edit_form: # (4) Default edit tab on content block.
title: 'Edit'
route_name: entity.block_content_type.edit_form
base_route: entity.block_content_type.edit_form
entity.block_content.delete_form: # (5) Non-default delete tab on content block.
title: Delete
route_name: entity.block_content.delete_form
base_route: entity.block_content.canonical

动态Drupal8 Local Tasks菜单

有时,静态的Drupal8 tab菜单不能完全满足我们在Drupal8开发中的需求,比如views、content 的翻译,
要添加动态的Drupal8 tab菜单,你的example.links.task.yml应该如下:
example.local_tasks:
deriver: 'Drupal\example\Plugin\Derivative\DynamicLocalTasks'
weight: 100
在derivative 类中生成动态Drupal8 tab菜单,src/Plugin/Derivative/DynamicLocalTasks.php
namespace Drupal\example\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

/**
 * Defines dynamic local tasks.
 */
class DynamicLocalTasks extends DeriverBase {

/**
 * {@inheritdoc}
 */
public function getDerivativeDefinitions($base_plugin_definition) {
// Implement dynamic logic to provide values for the same keys as in example.links.task.yml.
$this->derivatives['example.task_id'] = $base_plugin_definition;
$this->derivatives['example.task_id']['title'] = "I'm a tab";
$this->derivatives['example.task_id']['route_name'] = 'example.route';
return $this->derivatives;
}
}