logo

额外区块类型 (EBT) - 全新的布局构建器体验❗

额外区块类型 (EBT) - 样式化、可定制的区块类型:幻灯片、标签页、卡片、手风琴等更多类型。内置背景、DOM Box、JavaScript 插件的设置。立即体验布局构建的未来。

演示 EBT 模块 下载 EBT 模块

❗额外段落类型 (EPT) - 全新的 Paragraphs 体验

额外段落类型 (EPT) - 类似的基于 Paragraph 的模块集合。

演示 EPT 模块 滚动

滚动

为 Drupal 创建 Views 显示样式

03/10/2025, by Ivan

创建一个 Views 显示样式插件看起来可能是一项复杂的任务,但实际上比你想象的要简单。下面是一个带源码的分步指南。

你可以在这里下载现成的代码:TARDIS(尽管它还在开发中)。如果你需要 Drupal 8 模块的入门介绍,请查看这个 Drupal 8 基础模块构建实用指南

.info.yml

首先,在 /modules/custom 下为你的模块创建一个名为 tardis 的文件夹。在其中放置一个名为 tardis.info.yml 的文件,内容如下:

name: TARDIS
type: module
description: 'Provides a View display style that renders a list of year and month links to content in reverse chronological order.'
package: Views
core: '8.x'
dependencies:
  - drupal:views

类 Classy

现在是时候创建插件类了。在 src/Plugin/views/style 文件夹下创建一个名为 Tardis.php 的文件,并粘贴以下代码:

<?php

namespace Drupal\tardis\Plugin\views\style;

use Drupal\core\form\FormStateInterface;
use Drupal\views\Plugin\views\style\StylePluginBase;

/**
 * Style plugin to render a list of years and months
 * in reverse chronological order linked to content.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "tardis",
 *   title = @Translation("TARDIS"),
 *   help = @Translation("Render a list of years and months in reverse chronological order linked to content."),
 *   theme = "views_view_tardis",
 *   display_types = { "normal" }
 * )
 */
class Tardis extends StylePluginBase {
  ...
}

让我们看一些关键点:

 * @ViewsStyle(
 *   id = "tardis",
 *   title = @Translation("TARDIS"),
 *   help = @Translation("Render a list of years and months in reverse chronological order linked to content."),
 *   theme = "views_view_tardis",
 *   display_types = { "normal" }
 * )

这些注释很重要,它们为我们的插件打下了基础。如果你忘记添加这些,代码将无法正常工作。

class Tardis extends StylePluginBase {

这是插件的基本定义。这也是必须的。

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['path'] = array('default' => 'tardis');
    return $options;
  }

定义基础选项,并为我们的插件提供一个重要的默认值。这是因为这个插件应该是可配置的。

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

接下来,我们像普通配置表单一样创建参数表单。更多信息请参考 Form API 文档

.module 文件

在 Drupal 8 中,.module 文件不是必须的,但主题信息应放在这里:

<?php

/**
 * @file
 * TARDIS Views module help and theme functions.
 */

/**
 * Implements hook_theme().
 */
function tardis_theme($existing, $type, $theme, $path) {
  // Store TARDIS preprocess theme functions in a separate .inc file.
  \Drupal::moduleHandler()->loadInclude('tardis', 'inc', 'tardis.theme');

  return array(
    'tardis' => array(
      'file' => 'tardis.theme.inc',
    ),
  );
}

基本上,我们将 预处理函数 委托到单独的文件中,这样更易于组织。

.theme.inc 文件

在模块目录下创建一个名为 tardis.theme.inc 的文件,并包含以下代码:

<?php

/**
 * @file
 * Theme for TARDIS views.
 */
function template_preprocess_views_view_tardis(&$variables) {
  ...
}

这段代码主要是获取所有节点的 创建日期,并生成一个关联数组传递给 Twig 模板进行最终渲染,同时保留表单中定义的其他选项。

Twig 模板

接着,在 templates 文件夹中创建一个名为 views-view-tardis.html.twig 的文件。为什么是这个名字?还记得教程开头的注释吗?

* theme = "views_view_tardis",

这意味着模板必须位于默认位置(/templates)并且文件名要将下划线替换为中划线,扩展名是 .html.twig

{#
/**
 * Default theme implementation for Views to output a TARDIS archive.
 *
 * Available variables:
 * - options: View plugin style options:
 *   - classes: CSS classes.
 *   - nesting: Whether months should be nested inside years.
 *   - path: Link path. Eg.: example.com/TARDIS/2016/03
 *   - time_pool: Two-dimension array containing years and months with content.
 *
 * @see template_preprocess_views_view_tardis()
 *
 * @ingroup themeable
 */
#}
...

首先,建议在文件开头提取 $variables 数组传入的所有变量。它们都整齐地存放在 $variables['options'] 中(在 Twig 中为 variables.options)。

然后,我们根据参数表单定义一些类:

{%
  set classes = [
    'views-view-tardis',
    options.classes
  ]
%}

并在模板中使用它:

<div{{ attributes.addClass(classes) }}>

剩余的代码就是提取有内容的月份和年份并显示 HTML 列表。这里 for 循环很关键:

{% for key, item in options.time_pool %}

它会正确生成每一个链接,例如:

<li><a href="/{{ options.path }}/{{ key }}/{{ subkey }}">{{ subitem }}</a></li>

额外的工作

最后,我们需要创建一个默认的 View 并导出它,以便用户快速使用。你会注意到在 /config/install/views.view.tardis.yml 中已经包含了默认视图。用户启用模块后就能立即使用这个默认视图。

我通过 admin/config/development/configuration/single/export 的单一导出表单创建并导出了它,参考了 Subhojit Paul 的优秀教程

就是这样!

现在你可以为 Drupal 8 编写你自己的 Views 显示样式插件了!请在下方留言。祝编码愉快!