Drupal - Check if it's the front page in the template
The variable you're looking for is called is_front
:
{% if is_front %}
The available variables for a template are documented at the top of the .html.twig file, however there is also a set of default variables available to all templates (which are not documented in every single template). You can find them in _template_preprocess_default_variables().
Note that if you want to provide $variables['is_front']
to templates that doesn't, you can add this into the concerned preprocess function.
function themename_preprocess_menu(&$variables) {
try {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
}
catch (Exception $e) {
$variables['is_front'] = FALSE;
}
}
It is done the same way in template_preprocess_page for page.html.twig
.
Same answer here
Assuming that the template you are using is page.html.twig, then the variable you are looking for is is_front
; front_page
contains the URL of the front page, initialized in template_preprocess_page()
with the following code.
$variables['front_page'] = \Drupal::url('<front>');
For other template files, Drupal doesn't provide any variables telling you if the user is visiting the front page. Using code similar to the one used from template_preprocess_page()
, you can set that variable in the preprocess function for the template you are using.
function mymodule_preprocess_HOOK(&$variables) {
// An exception might be thrown.
try {
$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
}
catch (Exception $e) {
// If the database is not yet available, set the default value.
$variables['is_front'] = FALSE;
}
}
Replace HOOK
with the template type (e.g. field for the field.hmtl.twig template).