You are here

function page_specific_class_preprocess_html in Page Specific Class 8

Same name and namespace in other branches
  1. 2.0.x page_specific_class.module \page_specific_class_preprocess_html()

Implements hook_preprocess_html().

File

./page_specific_class.module, line 15
This file adds a class to the body tag page-wise.

Code

function page_specific_class_preprocess_html(&$variables) {

  // Get current path.
  $current_path = \Drupal::service('path.current')
    ->getPath();

  // Get path from alias.
  $current_path = \Drupal::service('path.alias_manager')
    ->getPathByAlias($current_path);

  // Get settings from page specific class settings.
  $config = \Drupal::config('page_specific_class.settings');
  $enteredArr = explode(PHP_EOL, $config
    ->get('url_with_class'));
  foreach ($enteredArr as $values) {
    $urlWithClassArr = explode("|", $values);
    $url = trim(strtolower($urlWithClassArr[0]));
    if (isset($urlWithClassArr[1])) {
      $class = trim($urlWithClassArr[1]);
      $classes_array = explode(' ', $class);
      $front_page = \Drupal::service('path.matcher')
        ->isFrontPage();
      $enteredPath = \Drupal::service('path.alias_manager')
        ->getPathByAlias(Html::escape($url));

      // If current path and entered path by user in page class setting match,
      // then only add respective class.
      if ($current_path == $enteredPath) {
        foreach ($classes_array as $class) {
          $variables['attributes']['class'][] = Html::cleanCssIdentifier($class, []);
        }
      }
      elseif ($front_page && $enteredPath == "/<front>" || $enteredPath == "/*") {
        foreach ($classes_array as $class) {
          $variables['attributes']['class'][] = Html::cleanCssIdentifier($class, []);
        }
      }
    }
  }
}