Drupal 9:如何在路径URL中添加字段值并限制访问?
解决方案:Drupal 9 多语言站点自定义URL结构+访问限制
一、实现域名后添加分类法字段值的URL结构
要达成www.example.com/[分类值]/[语言]/[内容路径]的URL结构,可通过以下步骤实现:
配置Pathauto路径模式
- 安装并启用Pathauto模块,针对目标内容类型创建自定义路径规则。假设分类法字段为
field_category,路径模式可设为[node:field_category:entity:name]/[language:code]/[node:title]。 - 调整语言检测设置:进入
/admin/config/regional/language/detection/url,取消“在路径前添加语言前缀”的默认行为,同时确保系统通过URL中的语言代码识别语言。这样Pathauto生成的路径会自动包含分类值+语言代码+内容路径的结构。
- 安装并启用Pathauto模块,针对目标内容类型创建自定义路径规则。假设分类法字段为
自定义路径处理器(复杂场景可选)
如果Pathauto的默认规则无法满足动态验证需求,可编写自定义模块实现路径解析逻辑。示例代码片段:<?php namespace Drupal\custom_path\PathProcessor; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; use Symfony\Component\HttpFoundation\Request; class CustomPathProcessor implements InboundPathProcessorInterface { public function processInbound($path, Request $request) { // 匹配 /分类值/语言代码/内容路径 格式的路径 if (preg_match('#^/([^/]+)/([a-z]{2})/(.*)$#', $path, $matches)) { // 验证分类值对应的分类术语是否存在 $term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); $term = $term_storage->loadByProperties(['name' => $matches[1]]); if (!empty($term)) { // 重写请求路径,移除分类值并传递分类参数 $new_path = '/' . $matches[2] . '/' . $matches[3]; $request->attributes->set('custom_category', $matches[1]); return $new_path; } } return $path; } }在模块的
services.yml中注册该处理器:services: custom_path.path_processor: class: Drupal\custom_path\PathProcessor\CustomPathProcessor tags: - { name: path_processor_inbound, priority: 100 }
二、限制无分类法字段值的页面访问
可通过以下三种方式实现访问控制:
自定义节点访问钩子
在自定义模块中实现hook_node_access,检查节点是否包含分类字段值,无值则拒绝访问:<?php function custom_access_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) { // 仅针对目标内容类型(例如page)的查看操作 if ($node->getType() === 'page' && $op === 'view') { $field_value = $node->get('field_category')->getValue(); if (empty($field_value)) { return \Drupal\Core\Access\AccessResult::forbidden()->addCacheableDependency($node); } } return \Drupal\Core\Access\AccessResult::neutral(); }使用Content Access模块
安装Content Access模块后,针对目标内容类型创建自定义权限规则,仅允许访问包含分类字段值的节点。使用Rules模块
安装Rules模块,创建触发规则:当用户尝试查看节点时,检查节点是否存在分类字段值,无值则跳转至403禁止访问页面。
替代方案
若自定义URL结构配置成本过高,可采用更贴合Drupal默认逻辑的变体:www.example.com/en/[分类值]/about。只需在Pathauto中将分类字段放在语言前缀之后即可,访问限制逻辑与上述一致,配置更简单。
内容的提问来源于stack exchange,提问作者marf
相关产品推荐
相关产品推荐

