我知道如何在 Drupal 10 中定义路由并通过控制器创建关联的内容。但我现在想做的是将这些内容分成几个块,然后使用 Drupal 的布局功能将这些块组装到经典的 Drupal 基本页面中。问题是我找不到如何传递在块中创建动态内容所需的一些参数。
我尝试创建一个节点 ID 为 51079 且 url 别名为“example”的内容页面。 “arg”是我想传递给块的变量。然后我在自定义模块中定义了一条路线
example.landing_date:
# path: "/node/{nid}/{arg}"
path: "/example/{arg}"
defaults:
_controller: '\Drupal\node\Controller\NodeViewController::view'
# _entity_view: "node.full"
_title: "Example"
node: 51079
month_day: NULL
options:
parameters:
# nid:
# type: entity:node
arg:
type: string
requirements:
_permission: "access content"
arg: "[0-9]{2}-[0-9]{2}"
注释行是导致相同结果的替代方案。这种方法有两个问题: 1 - 我必须使用别名或非别名 url,这使多语言环境中的管理变得复杂。 2-当我访问 /example 时,它按预期工作,我有基本页面,并且块根据“arg”的默认值(空)显示。但是,如果我访问 /example/03-09,arg (03-09) 的值会正确传递到块,但节点会显示在标题下方,即页面标题重复。
我查看了核心节点模块中如何管理路由,我发现它们不是在routing.yml 文件中定义的,而是在 NodeRouteProvider 类中定义的。也许我还应该通过扩展 NodeRouteProvider 类来定义我的路线,但我不知道如何以及在哪里执行此操作。
最后我找到了alterRoutes的解决方案,感谢https://drupalsun.com/philipnorton42/2022/10/16/drupal-9-altering-routes-route-subscriber-service
protected function alterRoutes(RouteCollection $collection) {
/** @var \Symfony\Component\Routing\Route $augmented_node_route */
$augmented_node_route = $collection->get('entity.node.canonical');
$augmented_node_route->setPath('/node/{node}/{arg}');
$augmented_node_route->addDefaults(['arg' => NULL]);
$augmented_node_route->addOptions([
'parameters' => [
'arg' => ['type' => 'string']
]
]);
$augmented_node_route->setRequirement('arg', '[0-9]{2}-[0-9]{2}');
}
通过将“arg”默认设置为 NULL,这也允许访问“/node/{node}”(没有“arg”)
我不明白的是,为什么当我尝试实现相同的目标但在同一个 alterRoutes 函数中使用“新路线”(而不是更改原始路线)时,它不起作用,或者更准确地说它起作用,但复制了节点标题并且无法直接访问常用的节点选项卡(编辑、删除、修订等)
$route = new Route('/page/{node}/{arg}');
$route->addDefaults([
'_controller' => '\Drupal\node\Controller\NodeViewController::view',
'_title' => 'Page added through route subscriber',
]);
$route->addRequirements(
[
'_entity_access' => 'node.view'
]
);
$collection->add('myModule.node.canonical', $route);