7

I need Drupal to use a custom page template if the URL contains a particular _GET parameter.

In D7 I would do something like this in the theme's template.php:

function mytheme_preprocess_page(&$variables) {
      if($_GET['isCustomTpl'] == true)
        $variables['theme_hook_suggestions'][] =  'page__myCustomTpl';
}

It doesn't work in D8 though (I would have been surprised by the opposite, considering all the architectural changes in the theme layer).

Any ideas?

Bonus question: is it possible to define such a function in a module, so that i can release it publicly without having the users to edit their themes?

12

You can implement the new hook_theme_suggestions_HOOK_alter() hook.

Alters named suggestions for a specific theme hook.

This hook allows any module or theme to provide altenative theme function or template name suggestions and reorder or remove suggestions provided by hook_theme_suggestions_HOOK() or by earlier invocations of this hook.

You can use it like so

function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (\Drupal::request()->query->get('foo') == 'bar') {
    $suggestions[] = 'page__myCustomTpl';
  }
}

You can implement it in either a module or theme

  • 1
    Great, working perfectly! Hopefully it'll evolve into a fully-functional pjax module for d8! – Sifro Dec 22 '13 at 14:55
  • if I want to do it by theme, I must put this code in template.php file like drupal 7? and the theme file name must be page_myCustomTpl.html.twig? am I right? – shekoufeh May 29 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.