In Drupal each theme has its own settings page at admin/appearance/settings/themeName. This page has a form with standard settings like “Logo image settings” ,“Shortcut icon settings”, "fonts", "styles" for example.
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.
Create theme settings
Example How to add custom setting "logo footer":
<?php
/**
* @file
* Theme settings in this file.
*/
/**
* Implements hook_form_system_theme_settings_alter().
*/
function mytheme_form_system_theme_settings_alter(&$form, $form_state)
{
$form['logo_footer'] = array(
'#title' => t('Logo Footer'),
'#description' => t('This Is Logo Footer: png|jpg|jpeg'),
'#type' => 'managed_file',
'#upload_location' => 'public://logo-footer/',
'#upload_validators' => array(
'file_validate_extensions' => array('png jpg jpeg'),
),
'#default_value' => theme_get_setting('logo_footer'),
);
}
To see the custom settings go to admin/appearance/settings/themeName:
Note that theme authors can create complex, dynamic forms using advanced Forms API (auto-completion, collapsible fieldsets.)
to use a setting in a Twig file, we'll add a new variable to the Twig file by adding it with a preprocess function in your THEMENAME.theme file.
For example, to add our logo_footer
setting to the page.html.twig
file, add this to the mytheme
.theme
file:
<?php /** * Implements hook_preprocess_page(). */ function mytheme_preprocess_page(&$variables) { $fid = theme_get_setting('logo_footer'); if (!empty($fid)) { $file = File::load($fid[0]); } if (!empty($file)) { $variables['logo_footer'] = $file->url(); } else { $variables['logo_footer'] = '/themes/custom/zaanouni/assets/images/logo-white.png'; } }
Then in the page.html.twig
file, you can access logo_footer
like any normal Twig variable:
<a href="{{ path('<front>') }}">
<img src="{{ logo_footer }}" alt="{{ 'Home'|t }}" class="img-fluid img_footer">
</a>
How make default value for Theme Settings
1.Create mytheme.settings.yml
in mytheme/config/install.
2.Create a line for each setting.
logo_footer : "/themes/custom/mytheme/assets/images/logo-footer.png"
Conclusion:
- By leveraging custom theme settings, themers can create a variety of controls to help site builders customize their sites.
- I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.