Skip to content

Instantly share code, notes, and snippets.

@anavdesign
Last active April 15, 2018 16:59
Show Gist options
  • Save anavdesign/dff07b28edc0b6df1299172b4b9d4165 to your computer and use it in GitHub Desktop.
Save anavdesign/dff07b28edc0b6df1299172b4b9d4165 to your computer and use it in GitHub Desktop.
Drupal: Advance Theme Settings

Drupal 8 Advanced Theme Settings

Apppearance Form

In Drupal 8, themes can modify the entire theme settings form by adding a PHP function to either the THEMENAME.theme file or to a theme-settings.php file. In one of those files, a theme should use THEMENAME_form_system_theme_settings_alter(&$form, $form_state) hook function.

File: theme-settings.php

$form['custom'] = array(
    '#type' => 'fieldset',
    '#title' => t('Custom Text'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
);

$form['custom']['custom_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Add custom text'),
    '#default_value' => theme_get_setting('custom_text'),
    '#description' => t('This is a short description.'),
);

Set Default Values

In order to set the default value for any form element you add, you’ll need to add a config/install/THEME.settings.yml file with a simple line: SETTING_NAME: DEFAULT_VALUE.

File: THEMENAME/config/install/THEMENAME.settings.yml

custom_text: some value

In any of your theme’s PHP files, you can retrieve the value the user set by calling:

$custom_text = theme_get_setting('custom_text');

##Getting the settings’ values in your theme files

In order to use a setting in a Twig file, you'll have to add a new variable to the Twig file by adding it with a preprocess function in your THEMENAME.theme file.

File: THEMENAME.theme

function THEMENAME_preprocess_page(array &$variables) {
  $variables['custom_text'] = theme_get_setting('custom_text');
}

Then in the node.html.twig file, you can access foo_example like any normal Twig variable:

File: node.html.twig

{{ custom_text }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment