Creating Advanced Theme Settings
In the Drupal administration section, each theme has its own settings page at admin/Appearance/Settings/themeName. This page contains a form with standard options such as "Logo image settings" and "Shortcut icon settings".
In Drupal 8, themes can modify the entire theme settings form by adding a PHP function either in the THEMENAME.theme file or in the theme-settings.php file. In one of these files, the theme must use the hook function THEMENAME_form_system_theme_settings_alter(&$form, $form_state). See “Forms API in Drupal 8” and the full list of Form and render elements, as well as documentation for hook_form_FORM_ID_alter() to explore the full flexibility of the forms API.
Here’s an example: if you have a theme named “foo” and want to add a text field with the default value "blue bikeshed", add the following to foo/foo.theme or foo/theme-settings.php:
function foo_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id = NULL) { // Work-around for a core bug affecting admin themes. See 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."), ); }
To set a default value for any added form element, add a config/install/THEME.settings.yml file with a simple line: SETTING_NAME: DEFAULT_VALUE. For our foo theme, edit foo/config/install/foo.settings.yml and add the following line:
foo_example: blue bikeshed
In any of your theme’s PHP files, you can get the user-set value by calling:
$foo_example = theme_get_setting('foo_example');
Note that theme authors can create complex dynamic forms using the advanced Form API (autocomplete, collapsible fieldsets).
Accessing settings values in your theme files
To use a setting in a Twig file, you must add a new variable to the Twig template using a preprocess function in your THEMENAME.theme file.
$variables['varname'] = theme_get_setting('varname')
For example, to add our foo_example setting to the node.html.twig file, add this to foo.theme:
<?php function foo_preprocess_node(&$variables) { $variables['foo_example'] = theme_get_setting('foo_example'); }
Then in node.html.twig, you can access foo_example like any regular Twig variable:
{{ foo_example }}
More Information
See the Drupal 8 change record: https://www.drupal.org/node/2382645
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.