3

Suppose I have an alias like http://www.example.com/en/the-new-webpage.html.

I want to get the the-new-webpage.html part in hook_preprocess_html(). The language code might change into 'ja' or some other code due to the language availability. So I can't get the URL and pass it to str_replace() to replace the language part. Is there a function or a way to get the alias part without the language code?

0

1 Answer 1

2

Since you just need the last part of the path, you can use the following code in a hook_preprocess_html() implementation.

$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}

Starting with Drupal 8.8.0, some Drupal core service has been renamed, as described in The Path Alias core subsystem has been moved to the "path_alias" module. As consequence of that, in Drupal 8.8.0, Drupal 9.x, and Drupal 10.x, the path.alias_manager service has been replaced by the path_alias.manager service.
The previously shown code needs to be changed to the following one.

$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}

The path.current service has not been renamed, neither in Drupal 9.x nor in Drupal 10.x.

0

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.