I have the following code in a Drupal's 8.2 my_module.module file.
/**
* Implements hook_preprocess_page().
*
*/
function my_module_preprocess_page(&$variables) {
if( \Drupal::routeMatch()->getRouteName() == my.route )
doSomething();
}
function doSomething(){
//code here
}
My intention is to run some code only when the user requests my.route.
Does Drupal have any function like this?
function my_route_preprocess_page(&$variables) {
//code here
}
Thanks in advance.
No, Drupal 8 doesn't have a function like which you want (preprocess a route) because the idea for the theme preprocess is to preprocess the variables that will be available on your twig template, and preprocess a route doesn't make sense.
In this way, you can follow like you started, preprocessing a page, block, view or etc validating by your route.
function theme_preprocess_page(&$variables) {
$current_route = \Drupal::routeMatch();
$route_name = $current_route->getRouteName();
if($route_name == 'myroute.hook') {
//your logic here
}
}
You can read more about the available theme preprocess for Drupal 8 on the Drupal doc: theme.inc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With