Syndicate

Feed

Theming Drupal 6 from the module layer

Sometimes, you need to change the HTML markup output by some module, and you want your changes to keep whichever theme you will use. The need came up for me recently when I had to provide special markup for pages that display a webform. I had to quickly put together a module for a client, a module that would provide a template file, which I decided to name (arbitrarily) page-webform.tpl.php.

The situation may arise for you as well, so I will share my technique with you. Say you want to provide a template file for all pages that display one node of a content type with machine-readable name CONTENT_TYPE_NAME. And say you want to use a module to provide such template. Say you decide to name your module special_page.

You start with creating a DOT info file for your module. The name of which would be in our case special_page.info.

;$Id$
name = Special Page
description = Provides a template file for my content type CONTENT_TYPE_NAME.
core = 6.x

Then you go about creating your DOT module file, ie: special_page.module.

<?php
// $Id$
/**
 * @file
 * Module that provides a special template for pages that show 
 * ONE node of content type CONTENT_TYPE_NAME.
 */

You probably should implement HOOK_help() in your module, but I will skip that, and cut the chase to what we really need.

At this point, you need to tell the theme system to use your template, and to use it only in certain situations. Your 'situations' will differ from mine. In my case, I wanted the theme system to use my template on a node page, hence any page with path node/nid, yet only on pages that show the node in view 'mode', so I did not want the template to be used when the path is node/nid/edit for example. There are many ways to skin the cat here. I decided to use the fact that a $node object is passed to the page.tpl.php template only when the page is a node page, as you will see in the following code snippet. Here, I will make use of a preprocess function to pass on to the theme system a suggestion about a new module-supplied template.

function special_page_preprocess_page(&$variables) {
  // If this is a node page (not a list of nodes page) and
  // the node is shown in 'view' mode rather than 'edit' or whatever.
  if (isset($variables['node']) && (arg(2) === NULL)) {
    // If the content type of that one node is 'CONTENT_TYPE_NAME'.
    if ($variables['node']->type == 'CONTENT_TYPE_NAME') {
      $variables['template_file'] = 'page-CONTENT_TYPE_NAME';
    }
  }
}

Then feel free to create such template file. As a reminder, no need to add the tpl.php extension to the value you assign to $variables['template_file']. Also, that name can be anything, I am just following conventions here by prefixing with page, as in page-SOMETHING.tpl.php. Make sure that the name you provide here matches the name of your template file.

Then, you are faced with a small problem: the template file will need to be placed in the theme folder in order to be picked up by Drupal's theme system. But you don't want that. So what to do? Here comes a situation where we can use the module hook HOOK_theme_registry_alter(). For the theme hook you want to provide special theming for (hook in theme parlance here), you will have to tell Drupal Hey, Drupal, please look in my module folder over here, you may find a template file you will need.

EDIT: As of Drupal 6.7, this last step should no longer be necessary. See this page in the Theming Guide on Drupal.org for details. I haven't had the chance to re-test my module without the following snippet.

function special_page_theme_registry_alter(&$theme_registry) {
  $theme_hook = 'page'; // my hook name
  // Get the path to this module
  $modulepath = drupal_get_path('module', 'special_page');
  // Add the module path on top in the array of paths
  array_unshift($theme_registry[$theme_hook]['theme paths'], $modulepath);
  // dsm($theme_registry[$theme_hook]['theme paths']);
}

And you are done.

A word on performance

What's more...

The hook function HOOK_theme_registry_alter() is called only when the theme registry is rebuilt, that is, when you clear your Drupal cache. (It is called for all modules that implement it of course.)

The hook is NOT called at every page refresh :-)

What a relief.

To test this, uncomment the dsm() call.

Last edited by Caroline Schnapp about 12 years ago.

Comments

Redemption

The Drupal theme system has redeemed itself in my book.

Great write-up. Thank you very much for taking the time.

Drupal 6 is just great with theming

I dot not want to go back, Abuchanan.

I don't agee with your

I don't agee with your comment. I like go back to watch the film again. it's a good Suspense film I love the film.
I must say I am very impressed with the way you and your site effectively films are very informative.
dvdmallonline

Thank you for the great

Thank you for the great article I did enjoyed reading it, I will be sure to bookmark your blog and definitely will come back from again. Hey, Today is 1st day I have read your blog but believe me you are ready good in writing.
Buy DVDs Online | Cheap DVD Box Set

I think the partnership that

I think the partnership that she has made with the schools is so good. So happy with the ideas that she is offering. The food will definitely benefit the kids so much.
The Closer Seasons 1-7|Drop Dead Diva Seasons 1-4 |Pretty Little Liars Seasons 1-3

I really liked it. Keep

I really liked it. Keep sharing such excellent post like this in future too. Informative and good article. I like it very much. Have very interesting content to read out. Thanks dude.
The Killing Seasons 1-3|how i met your mother seasons 1-8 |I Love Lucy Seasons 1-8

I personally was not too

I personally was not too follow the theme for drupal. In my opinion, the quality and performance of the application work is my priority so that the design and theme of the display is not a thing that means to me. recuperação de dados

Latest themes from the

Latest themes from the Drupal is already widely used by computer users. In my opinion, with the theme, I can change the look of the website that I have had to become more attractive. In addition, I was able to learn to operate drupal better. Breast Augmentation Houston

The theme is in drupal is

The theme is in drupal is quite diverse, I personally quite keen to replace the existing theme in my blog. If the theme is in the drupal is quite simple and not overdone, I am very keen to use it. Dan Lozano

This makes you less

This makes you less believable, and some may still be on the fence about Lew Rockwell after reading your emotional arguments and personal attacks.
Merkur online spielen
Triple Chance kostenlos

Can you help me how to make

Can you help me how to make HOOK_help() for this case?

With the module like this, I

With the module like this, I think it could be very helpful for computer users who are learning to use Drupal, like me. I personally feel this module greatly simplify the process of learning what I did. Selfless Giving

Some of what I have written

Some of what I have written about is state-of-the-art, and you might not even find it on the usual pro-tech or transhumanist websites like kurzweilai.net, hplusmagazine.com or acceler8or.com. e.g. I recently wrote about unsupervised semantic parsing (and indirectly about unsupervised ontology induction), which is a BIG BIG DEAL in A.I. research... but is not exactly the sort of thing you will see discussed on kurzweilai.net, for instance.
fairtex shorts

The thoughts are very well

The thoughts are very well laid out and it was refreshing to read. You published very helpful information, finding a reliable password manager is not that easy, keepassx looks like a good one. I'll give it a try during the next few days, thanks
Gary Wilson

Perfect!

Exactly what I needed. Thanks.

Thanks for the thanks

Glad this could help you, Frank, and best of luck with your development.

This looks like a great module: http://drupal.org/project/custompage

I admire your efforts and

I admire your efforts and your idea that you put into this blog. Thanks for the information. Really lovely and useful for me and will refer my friends to this blog.
coupon pig

The theme is in drupal is

The theme is in drupal is quite interesting to try. I personally have tried to use the existing theme in Drupal to update the look of the blog that I have. In my opinion, what should be done is not that difficult. website

Ah, now I get it, you can

Ah, now I get it, you can inject the custom template into the theme system but without tying the template to a particular theme or having to copy it to multiple theme folders (so for example you can allow users to select their own theme and the template will always still be available). I guess that's what you were saying in the first sentence! D6 subthemes are great e.g. for adding a template to a single theme but this is another level of flexibility.

Thanks for another insightful post!

Yeah, my goal is better explained in your comment

That's it exactly.

Hello, what if the page I

Hello, what if the page I wanna style is a menu callback? how do i do it?

Menu callback

That menu callback function returns some output, ie: markup. Well, that output is probably generated with a theming function. If it is, then it is business as usual: create a template, and use the method described above.

what if...

hi, excellent tutorial. Only one question, your code works like a charm, but the module removes any possibility to the user to modify the .tpl.php from the theme directory.

What if i should only need to add a piece of text, or a div on the $content variable without theming the output? Should it be possible to do it from the module?

Thanks in advance

Adding to $content

What if i should only need to add a piece of text, or a div on the $content variable without theming the output?

For this, you need to implement the module hook HOOK_nodeapi() in your module. Use $op = 'view'.
You will find more explanation on this here.

Great.

Just what I was looking for. This should be in the Drupal docs!

thanks

Hi
I was looking for this for a couple hours :) finally. Thanks a lot.

Glad you found it

:-)

Since drupal 6.9, the need

Since drupal 6.9, the need to put the template file inside the theme dir is no more. it can now reside in the module dir and drupal will take a peek there.

http://drupal.org/node/223430

That's fabulous!

And extremely important. I will update the tutorial.

Thank you very much!

Very useful

Very useful

Thanks

This was very helpful!

Nice tutorial..

New method in drupal 6 for theming as compared to drupal 5.

good articles always here...

Thanks

Custom theme hook

I find that this works if using MYMODULE_preprocess_page() but if I'm preprocessing a custom theme hook, the override does not apply and the template in my modules direcotry is still sued instead of the one copied into my theme's directory.

Does this only work with MYMODULE_preprocess_page()?

Following up, naming

Following up, naming conventions seem to be the cause of my issue.

Brian

That last step where we edit the theme registry is no longer necessary. Read the tutorial again. All you have to do is register a theming function for your custom hook, and, when you do, don't forget to specify the name of the template you will use.

thanks

This is informational and came in handy for me. Thanks for the input here.

Ah

This site is a real winner

I had a bit of trouble theming drupal from the module layer myself. I actually had to pass the task on to my lecturer at the time.

Keep up the great posts.

Simon

Then enable the special_page module

Haha then you enable the special_page module you just created :) That was five minutes I'm not getting back. I stuck a div with a string in my page-something.tpl.php thinking that would just overwrite my page content but it didn't and I can't see anything happening. What have I done wrong?

have a .info and .module copy and pasted into a special_page folder replaced CONTENT_TYPE_NODE with page in the if-statement and changed the template_file to 'page-something'

I then enabled the module (eventually), refreshed the cache, made a page and viewed it. I then refreshed the cache a couple more times. dsm has me entering the if-statement but nothing happens.


function special_page_preprocess_page(&$variables) {
// If this is a node page (not a list of nodes page) and
// the node is shown in 'view' mode rather than 'edit' or whatever.
if (isset($variables['node']) && (arg(2) === NULL)) {

// If the content type of that one node is 'CONTENT_TYPE_NAME'.
if ($variables['node']->type == 'page') {
$variables['template_file'] = 'page-something';
dsm($variables);
}
}
}

//my .tpl.php has (maybe that's not enough)

What the what!!!

then I'm assuming it's drupal_render(something) to show the content with the new template??? Sorry I'm an utter newb with drupal.

No idea

Actually I have no idea what I have to type to print out the $content var in the .tpl.php

Geez, thanks

Caroline, thanks for the detailed instructions. I'm helping my wife with her drupal site and your steps really came in handy!

Thank you...

Thank you, Edward! :)

new comer of drupal

I am learning to use drupal to setup my another commercial website in order to save time and money.
useful information thanks

Great Technique Caroline

I have a couple of Drupal blogs I am playing with and tutorials like these are helping greatly. I swear you drupal module developers are genius - I have saved mad money by not taking any drupal college courses, but instead of running across blogs like this one.

Thank you for everything,
Jerry Chan :)

Had some issues...

I couldn't get the template file to work as set in special_page_preoprocess_page() until I changed


$variables['template_file'] = 'page-CONTENT_TYPE_NAME';

to

$variables['template_file'][] = 'page-CONTENT_TYPE_NAME';

Interestingly, in both cases the dsm returned the same values. Something else in the mix I guess. I still had to use the theme_registry_alter code as well.

This was in Drupal 6.14.

Thx for the article. I had no clue about the the theme registry alter function's existence.

Got it

Helpful article, thanks. I concur w/ the previous poster about setting $variables['template_file'][] in order to get things working. However I *was* able to get the template file picked up w/o using hook_theme_registry_alter by specifying the template name in my module's hook_theme function. Something like:

function special_page_theme(){
    return array(
        'comment' => array(
            'template' => 'blog-comment',
            'arguments' => null
        )
    );
}

That did the trick. Without the template called out there, Drupal wasn't picking it up.

Thanks for pointing me in the right direction!

Reid

I love Drupal! What about you?

I have a couple of Drupal blogs I am playing with and tutorials like these are helping greatly. I swear you drupal module developers are genius - You should get far cry 3 (just a quick tip) to better handle drupal. I have saved mad money by not taking any drupal college courses, but instead of running across blogs like this one.

Thanks,
Michel,

wonderful

Really appreciate this wonderful post that you have provided for us.

nice

This site is really nice. I like the colour and the interface.

Magnificent post

Magnificent post. Surely, I got a real information about related topic. We greet for your helpfully job.
Himachal Packages | Himachal Tourism Packages

useful

I actually loved the article. It is very useful to me and I totally agree together with your conclusions and will eagerly wait for new posts

cv's that are too long.

cv's that are too long. trust me 8 pages is way too long. conversely using a really small font with no blank lines to make it fit onto 3 pages doesn't fool me at all.

A theme in an application it

A theme in an application it could be one thing that is forgotten a lot of developers. This is reasonable, but you really should pay attention to both. Joyetech eCab

There are many types of

There are many types of modules that can be found which is consistent with the many things that you need. When you need a module on the theme then you need to choose the right module. painters sacramento

Great effort

Great efforts and great idea that you put into this blog. Thanks for the information. Very usefull

well-written

Great Post. I have not been visiting the site recently. Took a visit again and there were some great comments on the site. Excellent post. Keep up the good work.

Rare write-up

Twin Fountains EC will be accessible with Woodlands MRT station & Admiralty MRT station. It is also near to Vista Point Shopping Mall, Causeway Point Shopping Mall, Cold Storage, Shop N Save, and many more.
Woodlands EC

At this point, you need to

At this point, you need to tell the theme system to use your template, and to use it only in certain situations. Your 'situations' will differ from mine. In my case, I wanted the theme system to use my template on a node page, hence any page with path node/nid, yet only on pages that show the node in view 'mode', so I did not want the template to be used when the e-papierosy path is node/nid/edit for example. There are many ways to skin the cat here. I decided to use the fact that a $node object is passed to the page.tpl.php template only when the page is a node page, as you will see in the following code snippet. Here, I will make use of a preprocess function to pass on to the theme system a suggestion about a new module-supplied template.

cheap custom essay writing services

Most university, college and high school students have benefited from having a coach at some point in their lives, either as a member of sports team, or as cheap custom essay writing services a participant in an individual sport.

Good thoughts and well-written

Great Post. I have not been visiting the site recently. Took a visit again and there were some great comments on the site. Excellent post. Keep up the good work.
Belgravia Villas

Thank you for taking the

Thank you for taking the time to publish this information very useful!I’m still waiting for some interesting
logo mats

excellent

Great blog. hope to read more from author. Hedges Park Condo, Topiary EC, Twin Fountains Woodlands

Ecopolitan EC is a 99-years

Ecopolitan EC is a 99-years leasehold Punggol EC development located at Punggol Walk in District 19. With expected completion in mid 2016, it comprises of TBA towers with TBA units and stands TBA storeys tall. It is situated right beside Punggol MRT Station. Future residents will be able to access the nearby Compass Point and Rivervale Mall which is a short drive away for some family fun and gatherings. A truly unique lifestyle awaits you.
Ecopolitan

Several buses are available

Several buses are available near Jewel at Buangkok along with shopping centers and restaurants. Jewel at Buangkok is also near to Compass Point as well as Hougang Green Shopping Mall. Entertainment for your loved ones and friends is therefore at your fingertips with the full condo facilities as well as the amenities near Jewel at Buangkok.
Buangkok New Launch

J Gateway has full and

J Gateway has full and unique facilities, which includes a guard house, clubhouse, children's playground, swimming pool, Aerobic/Yoga room, piano room, pool room, indoor gym, hydrotherapy beds, hydrotherapy baths, reading room, function room, onsen, jacuzzi.
J Gateway

Several buses are available

Several buses are available near Coral Edge Residences along with shopping centers and restaurants. Coral Edge Residences is also near Waterway Point, the shopping, dining and entertainment hub which is scheduled to open in 2 years time. Also, it is right beside Punggol Waterfront. Entertainment for your loved ones and friends are therefore at your fingertips with the full condo facilities as well as the amenities near Coral Edge Residences .
A luxurious lifestyle awaits you
Coral Edge Residence

Designed by renowned

Designed by renowned architect Ole Scheeren, the project is connected to Bugis MRT Interchange that will link the East-West Line and the upcoming Downtown Line. Duo
Residences has full and unique facilities, which includes a guard house, clubhouse, children's playground, swimming pool, piano room, pool room, indoor gym,
hydrotherapy beds, hydrotherapy baths, reading room, function room, onsen, jacuzzi.
DUO Residence

This website has very good

This website has very good content. Your writes of blog are really helpful for me. I got many threads and Important point for my site developing sites. What's your the next post? Waiting for you. Landowners

I swear you drupal module

I swear you drupal module developers are genius - I have saved mad money by not taking any drupal college courses, but instead of running across blogs like this one. http://www.youtube.com/watch?v=rMJn9Uiml_8

Forestville EC is also near

Forestville EC is also near elite schools such as Singapore American School, Greenwood Primary School, Si Ling Primary School and Qihua Primary School.
It is also near to Singapore Sports School and Innova Junior College in Woodlands
Forestville EC