Let Drupal 8/9 templates know the difference between the default logo and custom logo
Do you want to add a different class to the site logo depending on if it’s the default logo or custom? Maybe! If so, here’s how.
Create a variable in the .theme
file.
Normally, the site logo is used in the block--system-branding-block.html.twig
so that’s where I want a variable available. Therefore I’m going to use a preprocess function for blocks.
function my_theme_preprocess_block(&$variables) {
$variables['is_default_logo'] = \Drupal::config('my_theme.settings')->get('logo.use_default');
}
- Replace
my_theme
with your theme’s machine name. - Replace
is_default_logo
with what you’d like to call the variable. The variable will be a Boolian akatrue
orfalse
.
Use the logo in the twig template
Edit the block--system-branding-block.html.twig
template which you should be able to find in the theme’s templates
folder.
Find where {{ site_logo }}
is being used and craft your conditional statement. If we’re using the default logo do this, or else do that. For example:
{% if is_default_logo %}
<img class="default-logo" src="{{ site_logo }}">
{% else %}
<img class="custom-logo" src=" {{ site_logo }}">
{% endif %}
You could also do this:
<img class="{% if is_default_logo %}default-logo{% else %}custom-logo{% endif %}" src="{{ site_logo }}">
It depends on how much you want the HTML to differ.
Note about subthemes
If for some reason you need to make this change in both a base theme and a subtheme you may need to remake the variable in the .theme
file.
I mean to say, duplicate the preprocess function above in the subtheme’s .theme
file being sure to change the theme’s machine name.
Thank you to the kind people at Drupal Answers Stack Exchange.