Drupal 8 Create custom content type templates - custom page template for particular content type

 Sometimes you need to create a page template for a specific content type so that you can customize it. First enable debug mode, so you can see “File name suggestions” in comments inside your code. 

Drupal allows you to create content types for node templates by the following  naming convention    

node--content-type.html.twig. But things aren’t so simple for page templates. Drupal does not automatically detect page templates for content types purely based on the naming convention. Fortunately it just takes a few lines of code and you can create a page template for any content type you choose.

Page template

To tell Drupal to use the page template for a content type, you can implement hook_theme_suggestions_page_alter(). This hook is used whenever a page.tpl.php template is used and allows you to suggest alternative templates.

In this case, you are going to tell Drupal to use a specific page template for a specific content type, for do that add this code in “.theme” file in you theme.

/**

* Implements bedrupal_suggestions_page_alter().

*/

function example_theme_suggestions_page_alter(array &$suggestions, array $variables) {

if ($node = \Drupal::routeMatch()->getParameter('node')) {

$suggestions[] = 'page__' . $node->bundle();

}

}

Now you can copy the template page.html.twig and paste in “/template/layout/” folder under your custom template, and rename in “page–customposttypename.html.twig”.

Clear cache, reload single custom post type page, and in “inspect” mode, you can see your new page under.

Node teamplate

Now create a folder “node” under “themes/custom/your_theme/template”, that’ll be the folder that contain all your custom post type template files.

Now copy the file “node.html.twig” from “modules/node/templates/” in folder “node” created before and rename in “node–customposttypename.html.twig”.

This is the file that wrap all content.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...