2

using D8, I'd like a twig template for a page I've created based off the path of the page and not node %. I look in my twig suggestions and all I see are:

page--node--8.html.twig
page--node--%.html.twig
page--node.html.twig
page.html.twig

As template suggestions. However, as I'm working in multiple environments and don't know what the node number will be when I actually create this page I'd like to just base it off the path I've set for the page which is '404-error'. Anyone know how to do that?

I'm imagining something like page--node--404-error.html.twig

However that doesn't seem to work (I tried it).

2
  • The only available template suggestions are the ones that are defined. If you disable caching and enable twig debug, you can view what the suggested templates are in the source code of the page. drupal.org/docs/8/theming/twig/debugging-twig-templates
    – Kevin
    Commented Sep 15, 2016 at 0:22
  • After that, you would have to do some logic for example in hook_preprocess_page, check if the current request is a node object, and if so, add on to the template suggestion list with 'page__node__' and add the path. I caution you here though, the paths may be too long to exist as a filename depending on what you're trying to do.
    – Kevin
    Commented Sep 15, 2016 at 0:23

1 Answer 1

2

You can add suggestions for the page template in a hook:

mytheme.theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

This is an example how to add a suggestion with the path for any page. You can narrow it down to the pages you are interested in and if necessary check for paths that are too long.

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.