I am trying to use PathMatcher::matchPath()
to match a string of paths using a wildcard pattern.
I'd like to match any path containing /topic*
so if the path matches, I'd like to add a body class for pages that have /topic
, /topic/foo
, /topic/bar
, etc..
The code I am using is the following.
function mytheme_preprocess_html(array &$vars) {
// Define the current path.
$current_path = \Drupal::service('path.current')->getPath();
// Define the pattern using a string.
$patterns = "/topic/*";
// If the path matches the pattern.
if (\Drupal::service('path.matcher')->matchPath($current_path, $patterns)) {
$vars['attributes']['class'][] = 'is-topic';
}
}
The code doesn't work to match this pattern so no class is added when I am on any of these pages.
My Xdebug info is as follows for the page that has the path topic/review-procedures
$current_path = /node/62
$path_alias = topic/review-procedures
Note that some pages with /topic/
in the path will not be nodes however, that is why I am trying to do the path matching.
Am I correctly using PathMatcher::matchPath()
?
matchPath()
is how Drupal core calls that method, and how the example in the documentation page does.\Drupal::service('path.current')->getPath()
return you? Install the Devel submodule Kint and tell us whatksm(\Drupal::service('path.current')->getPath());
inside that preprocess function returns you on the screen when visiting a relevant path. Is topic a node type for itself? Then you could check the route parameter to get the node, from there you have the type and can add a body class.path.current
service gets you the raw, un-aliased path , whereas you need to be matching against the aliasurl.path
cache context, but being at the top level of html.html.twig it might already be covered