1

With Drupal 8, in THEMENAME.theme I can generate a class based on the current node ID which will be inserted in the body tag :

In the THEMENAME_preprocess_html() function, i use :

$node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }

But how can i determine if we are on the contact page since it is not a node ?

  • 2
    Shot in the dark, but... $contact_form = \Drupal::routeMatch()->getParameter('contact_form'); – Kevin May 19 '17 at 13:11
7

Have you tried

\Drupal::routeMatch()->getParameter('contact_form');

This returns an object of type ContactForm when the user is on a contact page. A simple detection you can do with getRouteName():

if ('entity.contact_form.canonical' === \Drupal::routeMatch()->getRouteName()) {
  // huhu, a contact form
}

You can have a look at ./core/modules/contact/contact.routing.yml. There are all routes available.

  • I had a look at ./core/modules/contact/contact.routing.yml.and it seems to be the correct answer. But, it doesn’t work in THEMENAME_preprocess_html() but i can get the node id. Is there something else i should think off ? I’ve already cleared cache. – Sébastien Gicquel May 19 '17 at 13:41
  • I'm doing this $contact_form = \Drupal::routeMatch()->getParameter('contact_form'); if ($contact_form) { $variables['attributes']['class'][] = 'contact-test'; } – Sébastien Gicquel May 19 '17 at 13:42
  • 1
    @SébastienGicquel I've updated my answer. I tested this on my THEME_preprocess_html() and it works well. – RWAM May 19 '17 at 14:08
  • 1
    It works but i had to do if ('contact.site_page' === \Drupal::routeMatch()->getRouteName()) { // hello contact form } – Sébastien Gicquel May 19 '17 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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