4

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.

2 Answers2

4

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.

valdeci
  • 13,962
  • 6
  • 55
  • 80
0

No drupal does not have a preprocess function like that.

Actually the hook you uses is not hook_preprocess_page() but hook_preprocess_HOOK() and can be used for more than just pages so it does not know anything about routes. See hook_preprocess_HOOK() api.

melvin
  • 1,145
  • 8
  • 12