Score:1

Altering custom template from code

pt flag

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.

Score:2
bd flag

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']);
  }
}
pt flag
Thanks Berliner. I got too invested in a hook oriented solution and forgot all about the humble if-statement
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.