Different Page Template for Different Content Type in Drupal

This is one of the most frequently asked question in the interviews that
how can you provide different style(in terms of HTML & CSS) to any particulate page or any particulate content type in drupal?

 Here is the step by step answer for this question.
1:-First go to your themes folder(whichever theme is currently active) and search for this function in template.php file.

2:-Now Copy the following code inside this phptemplate_preprocess_page(&$vars)
   if (isset($vars['node'])) {
        // This code looks for any page-custom_content_type.tpl.php page
        $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type); 

In the above code,I am checking the value for node,if its value is set(means if we are opening any node in our drupal site),than this if condition will be true and the code inside will get execute.

We are using $vars['template_files'] array for loading the template file from themes folder.

3:-Next step is to create new content type(or you can use existing content type).
    For example I am creating product content type.

4:-Now create one content of product content type.

5:-Create one file named page-product.tpl.php inside themes folder.Here product is our custom content type.

6:-Once we click on any content of product content type,the above will search for the template file with page-product.tpl.php name.If file is present inside themes folder,then it will take this template file other wise it will style take from page.tpl.php.    

7:-In this page-product.tpl.php file,we can provide the different style(HTML & CSS).

These Steps are useful for particular content type.You can provide different template to particular  page also by adding this code:- 
$vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->path);
Here we have replaced $vars['node']->type with $vars['node']->path(for specific path).

And create the template file with the name of your page url. For examples if you want different template for
test_image url.So create file page-test_image.tpl.php

No comments:

Post a Comment