3

I have a page from different content type and I want to define a custom twig page template to these pages by their nid.

Eg. I have pages like node/2, node/4, node/20 and node/40 from the different content type and I want to apply page--custom.html.twig template only these specific pages by checking their ID.

Anyone know how to do this?

1

This page describes everything about naming conventions, twig template naming conventions.

As described it is possible to do like this: node--nodeid.html.twig, e.g node--2.html.twig.

The smartest way will be to implement the hook_theme_suggestions_page_alter(), like this:

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $nodes = [2, 4, 20, 40];
    if (in_array($node->id(), $nodes)) {
      $suggestions[] = 'page__custom';
    }
  }
}
  • I would recommend to use a swich block in your situation. – Jdrupal Apr 9 '18 at 13:25
  • 1
    in_array would be more readable – Clive Apr 9 '18 at 14:35
3

You can write a hook_theme_suggestions_page_alter()

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function YOUR_THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node->id() == 2 || $node->id() == 4 || $node->id() == 20 || $node->id() == 40) {
      $suggestions[] = 'page__custom';
    }
  }
  • Thank you Razeem. its worked! also if I have an absolute path, like views path (news, publication etc.). How can I check these absolute paths and nid together in the previous code? – Punya Ruchal Apr 9 '18 at 10:44
  • You can get the path of the node like $node->url() to get full path including http use something like$node->url('canonical', ['absolute' => true]) – Razeem Ahmad Apr 9 '18 at 11:18

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.