In a custom subtheme of classy base theme, I made a theme setting for referencing an image media file. Contents of file theme-settings.php:

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;
function mytheme_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

$opts = [
'#type'          => 'entity_autocomplete',
'#title'         => t("Image on startpage"),
'#description'   => t("Referencing an image."),
'#target_type'   => 'media',
'#selection_settings' => ['target_bundles' => ['image']],
if ($default_id = theme_get_setting('startpage_image')) {
// element stores an int ID, but default value has to be the loaded entity
$image = \Drupal::entityTypeManager()->getStorage('media')->load($default_id);
$opts['#default_value'] = $image;
$form['startpage_image'] = $opts;

Contents of file mytheme.theme:


function mytheme_preprocess_page(&$variables) {
$media_id = theme_get_setting('startpage_image');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'media.full');


And finally in the template page--front.html.twig the image is called by {{ startpage_image }}. But unfortunately, the image isn't shown (all caches rebuilt and flushed multiple times). In the last line in file mytheme.theme I also tried view($media, 'full') because I wasn't sure if media.full is the correct display mode that is built in into media core module — but this as well wasn't successfull.

Why is my code not working?

1 Answer 1


First you should add a test to see if it's the homepage or not, using


Then if you add a variables in your hook_page for exemple $variables['media_build'] you could get in the twig with {{ media_build }}.

  • Thank you, now it's working!
    – Madam Adam
    Feb 24, 2022 at 21:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.