logo

Palette - Make it Colorful🎨

Palette - Visual Page Builder, no design degree required.

Live Demo Download Palette

滚动

创建高级主题设置

01/10/2025, by Ivan

在 Drupal 的管理部分,每个主题都有自己单独的设置页面,路径为 admin/Appeance/Settings/themeName。该页面包含一个带有标准设置的表单,例如“Logo 图像设置”和“快捷图标设置”。

在 Drupal 8 中,主题可以通过在 THEMENAME.theme 文件或 theme-settings.php 文件中添加 PHP 函数来修改整个主题设置表单。在这些文件中的某一个里,主题需要使用函数 THEMENAME_form_system_theme_settings_alter(&$form, $form_state)。参见「Drupal 8 表单 API」以及完整的 表单和渲染元素列表,还有 hook_form_FORM_ID_alter() 文档,以了解表单 API 的完整灵活性。

以下是一个示例,如果你有一个名为 “foo” 的主题,并且想要添加一个默认值为 “blue bikeshed” 的文本字段,请将以下内容添加到 foo/foo.theme 文件或 foo/theme-settings.php 文件中:

function foo_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id = NULL) {
  // 针对影响管理主题的核心 bug 的解决方法。参见 issue #943212。
  if (isset($form_id)) {
    return;
  }

  $form['foo_example'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Widget'),
    '#default_value' => theme_get_setting('foo_example'),
    '#description'   => t("Place this text in the widget spot on your site."),
  );
}

要为任何添加的表单元素设置默认值,你需要在 config/install/THEME.settings.yml 文件中添加一行:SETTING_NAME: DEFAULT_VALUE。对于我们的 foo 主题,你需要编辑 foo/config/install/foo.settings.yml 文件,并添加如下行:

foo_example: blue bikeshed

在主题的任意 PHP 文件中,你可以通过以下方式获取用户设置的值:

$foo_example = theme_get_setting('foo_example');

请注意,主题作者可以利用高级表单 API 创建复杂的动态表单(例如自动完成、可折叠字段集)。

在主题文件中获取设置值

要在 Twig 文件中使用该参数,你需要通过在 THEMENAME.theme 文件中的预处理函数添加一个新的变量。

$variables['varname'] = theme_get_setting('varname')

例如,要将 foo_example 参数添加到 node.html.twig 文件中,请在 foo.theme 文件中添加:

<?php
function foo_preprocess_node(&$variables) {
  $variables['foo_example'] = theme_get_setting('foo_example');
}

然后在 node.html.twig 文件中,你可以像访问任何常规 Twig 变量一样访问 foo_example:

{{foo_example}}

更多信息

参见 Drupal 8 的变更记录:https://www.drupal.org/node/2382645