1

How can I programmatically remove blocks and other elements from a single custom template ?

In my custom modle I have defined a route to a controller which then loads a template which is also contained within the same module. I am successfully loading data from the controller into the template.

My issue is that the template inherits blocks and menu from the active theme which I need to remove but only in the modules template. For examples, the search and primary naviagation blocks are not supposed to display.

I had implemented :

function mymodule_export_preprocess_page(&$variables)
{
  unset($variables['page']['header']['searchform']);
  unset($variables['page']['menu_primary']);
}

But I later realised the seach and navigation blocks were removed not just in the module template but from every page on the site.

I also search for something like hook_page_alter that could not find anything appropriate for the task.

1 Answer 1

2

I think you're confusing themes and templates.

A theme is a set of files that control the display of your site via the use of template files, CSS and Javascript (mostly that, there is more if you dig).

A template file is just one of those files in a theme.

So the reason that the logic in your hook_preprocess_page affects every page, is that you apply those modifications unconditionally. Those preprocess hooks (when defined in a module) are applied to the active theme for any page request, whichever theme is used.

It's a bit difficult to suggest a specific solution in your case without seeing further code, e.g. from your controller, but you can try something along these lines (pseudo-code):

function mymodule_export_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() === 'route.to.controller') {
    unset($variables['page']['header']['searchform']);
    unset($variables['page']['menu_primary']);
  }
}
1
  • Thanks Berliner. I got too invested in a hook oriented solution and forgot all about the humble if-statement
    – sisko
    Commented Nov 26, 2021 at 17:15

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.