Drupal 9 theme setting custom field
A small note - if you need to add a custom field to the theme settings page in a Drupal 9 theme to output code (scripts) to a twig template, first add this to your mytheme.theme file (everywhere change mytheme to the name of your theme)
/**
* Implements hook_form_system_theme_settings_alter().
*/
function mytheme_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['mytheme_settings'] = [
'#type' => 'details',
'#title' => t('Custom Scripts Settings'),
'#open' => TRUE,
];
$form['mytheme_settings']['custom_scripts'] = [
'#type' => 'textarea',
'#title' => t('Custom Scripts'),
'#default_value' => theme_get_setting('custom_scripts', 'mytheme') ?: '',
'#description' => t('Enter your custom scripts here (e.g., JavaScript code or third-party script tags).'),
];
}
/**
* Implements hook_preprocess_html().
*/
function mytheme_preprocess_html(&$variables) {
$variables['theme_settings']['custom_scripts'] = theme_get_setting('custom_scripts', 'mytheme');
}
and then, in html.html.twig we add the code in block <head>
{% if theme_settings.custom_scripts %}
{{ theme_settings.custom_scripts|raw }}
{% endif %}