Skip to main content
It works with the path matcher as well, nice
Source Link
leymannx
  • 18.8k
  • 6
  • 72
  • 126

In your sample you were comparing the internal path (/node/123) with a path alias pattern (/topic/*). This won't work. You need to do the matching with the path alias instead.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  if (\Drupal::service('path.matcher')->matchPath($current_alias, '/topic/*')) {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

You could achieve thatthe same by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

You could achieve that by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

In your sample you were comparing the internal path (/node/123) with a path alias pattern (/topic/*). This won't work. You need to do the matching with the path alias instead.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  if (\Drupal::service('path.matcher')->matchPath($current_alias, '/topic/*')) {
    $variables['attributes']['class'][] = 'is-topic';
  }
}

You could achieve the same by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}
Source Link
leymannx
  • 18.8k
  • 6
  • 72
  • 126

You could achieve that by exploding the current request URI and then see if the first key is topic.

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $request_uri = ltrim(\Drupal::request()->getRequestUri(), '/');
  $args = explode('/', $request_uri);
  if (isset($args[0]) && $args[0] === 'topic') {
    $variables['attributes']['class'][] = 'is-topic';
  }
}