You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal 8中如何根据节点ID获取分类术语?

我来帮你搞定这个Drupal预处理的需求!你已经拿到了节点信息,接下来要获取分类术语并添加到body类里,我给你调整后的代码和详细说明:

完整的预处理函数实现
function custom_preprocess_html(&$variables) {
  // Add the node ID and node type to the body class
  $body_classes = [];

  // 先确保当前页面是节点页面,并且能拿到有效的节点对象
  if (isset($variables['node']) && $variables['node'] instanceof \Drupal\node\NodeInterface) {
    $node = $variables['node'];
    $nid = $node->id();
    $node_type = $node->getType();

    // 添加节点ID和类型类(保留你原来的需求)
    $body_classes[] = 'node-id-' . $nid;
    $body_classes[] = 'node-type-' . $node_type;

    // 替换成你的分类字段机器名!比如field_tags、field_category
    $taxonomy_field = 'field_category';
    // 检查节点是否有这个字段,且字段不为空
    if ($node->hasField($taxonomy_field) && !$node->get($taxonomy_field)->isEmpty()) {
      // 获取关联的所有分类术语实体
      $terms = $node->get($taxonomy_field)->referencedEntities();

      foreach ($terms as $term) {
        // 把术语名称转换成符合CSS规范的类名:小写+空格转横杠
        $term_class = 'taxonomy-term-' . strtolower(str_replace(' ', '-', $term->getName()));
        // 如果你怕术语名称会修改,也可以用ID生成更稳定的类:'taxonomy-term-id-' . $term->id();
        $body_classes[] = $term_class;
      }
    }
  }

  // 把自定义类合并到body的类数组中(Drupal 8+的标准写法)
  if (!empty($body_classes)) {
    foreach ($body_classes as $class) {
      $variables['attributes']['class'][] = $class;
    }
  }
}
关键步骤说明
  • 节点有效性检查:先判断当前页面是节点页面,避免在非节点页面(比如首页、视图页)触发报错
  • 分类字段适配:一定要把field_category替换成你实际使用的分类字段机器名,你可以在Drupal后台「结构>内容类型>目标内容类型>管理字段」里找到这个机器名
  • 术语类名处理:把术语名称转成小写、空格换成横杠,确保符合CSS类名的规范;如果担心术语名称后续会修改,用术语ID生成类(比如taxonomy-term-id-123)会更稳定
  • 缓存刷新:修改完预处理函数后,记得清一下Drupal的缓存,否则新代码不会生效

内容的提问来源于stack exchange,提问作者medievalmatt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:06:59