Drupal Development : Make a page template for dynamic page requests


Drupal is a fantastic content management system with an even more fantastic development community.

Recently through our own Drupal development projects, we came across a scenario that required the processing of dynamic (i.e. “Wildcard”) page requests to the same drupal page template. If I’ve lost you already , don’t worry! All we are trying to do is ensure the following page request scenarios are served by the same page template :

drupal-site.com/page1/randomrequest1 -> page–page1–wildcard.tpl.php
drupal-site.com/page1/randomrequest2 -> page–page1–wildcard.tpl.php

You can see in the two above scenarios, that the “page1” root request URI is the same, but the subsequent URI requests , “randomrequest1” and “randomrequest2” are different. What happens if you want to use the same page template for both random requests? Easy, you implement a check in the preprocess page hook in template.php!

In your drupal theme, you will have a file called template.php. This is where all the pre, post and other processing of variables are handled. This is where you can define a logical check that associates a page template with a particular request. There is technically a few ways you can accomplish this task, but the way we’ll show you is with the theme_preprocess_page function.

Here is the code that is used to break the request URI , analyze it, and associate a page template if the condition matches :

$path = request_path();
$fixed_path = explode('/', $path);
if (count($fixed_path) == 2 && $fixed_path[0] == 'page1')
$vars['theme_hook_suggestions'][] = 'page__page1__wildcard';

What does the above code do? It takes the request path, breaks up each request into an array, if the first URI is “page1”, then assign the respective page template. In our scenario, we were building a page that displays a user “profile” without having to create a separate drupal page for each user and assigning a page or node template respectively. What if you had 100 or 1,000 users? That would be tedious!

If a user enters drupal-site.com/page1/username ,then it will display our wildcard page template! Great! In the page template itself , we would be doing a few more checks and then displaying the user profile. I’ll save that for another post 🙂

Notify of

Inline Feedbacks
View all comments