Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8, hook_preprocess_ page by route

Tags:

drupal-8

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.

like image 467
Adrián-Cuéllar Avatar asked Oct 27 '25 05:10

Adrián-Cuéllar


1 Answers

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.

like image 139
valdeci Avatar answered Oct 30 '25 14:10

valdeci