2

What's the preprocess function for targeting the home page in a Drupal 8 site? Can I use a preprocess function that is called only for the home page?

1
  • 1
    The home/front page is now a page view called Frontpage with url/path of /node so you may have to give more details on what you're trying to achieve with the preprocess.
    – No Sssweat
    Aug 17, 2016 at 8:44

3 Answers 3

6

To target the front page in a preprocess function you need a condition, because for preprocess you can't use name suggestions:

function mytheme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    // your code
  }
}
1
  • not working on latest today D9
    – Augusto
    Jul 16, 2022 at 10:39
1

What you call home page, for Drupal is the front page. The suggestion given by system_theme_suggestions_page(), an implementation of hook_theme_suggestion_HOOK() from the System module, is page__front; similarly, system_theme_suggestions_html() suggests html__front. Both the suggestions are for the preprocess functions and the template files.

If by home page you mean a page that is not the front page, you need to write your own hook_theme_suggestions_HOOK() implementation that gives the right suggestion for that page. Keep in mind that the suggested template file is used only if it exists; otherwise, Drupal will use a different suggestion, or the default template file, if none of the suggested template files exist.

0

On today latest D9, you have:

 function THEMENAME_preprocess_html(&$variables) {
   if (\Drupal::service('path.matcher')->isFrontPage()) {
      // do something for your frontpage
   }
 }

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.