In my .tpl.php template files, I have several links and names of external websites. I would like to print these as variables, which are defined in template.php. That way, if I have to change a link, I can just change it in template.php and have them updated in all my tpl.php files.

How can I do this?

Steps I have tried

In this tutorial, it says you can define your variables in themename_preprocess_page(&$variables). You can then call them with <?php print render($page['your_variable_name']); ?>

However, when I try this, I just get a message stating Notice: Undefined variable: page in include(). The variable also doesn't print.

Also, if I use this method, can I use my variable in all tpl.php files or just the page.tpl.php file?


If you create a variable in themename_preprocess_page(&$variables), it should could be accessed using the variable name itself. Example

function themename_preprocess_page(&$variables) {
  $variables['my_new_variable'] = "String value";
  $variables['my_new_variable_array'] = array(); // Some renderable array.

And then in your template you could simply print the first variable directly

<?php print $my_new_variable; ?>

And render the renderable array using the render() function:

<?php print render($my_new_variable_array); ?>

Note: The array keys become the name of the variable, so please make sure to use a unique name to the keys.

  • This only seems to work in page.tpl.php file. It doesn't work in other tpl.php files (e.g. node.tpl.php). – big_smile May 27 '15 at 11:04
  • It also doesn't work for block.tpl.php – big_smile May 27 '15 at 11:13
  • 1
    It works for all theme functions @big_smile, it's the fundamental mechanism Drupal provides to add/edit variables in a template file. It works for page.tpl.php and block.tpl.php. The proof is the existence of functions like template_preprocess_block(), which core uses to do the same thing – Clive May 27 '15 at 12:15
  • @Clive Does that mean I need to have separate functions (e.g. themename_preprocess_page, themename_preprocess_block, themename_preprocess_node). Isn't possible to have one function that provides the variables for all templates? – big_smile May 27 '15 at 13:40
  • 1
    Yep, that's hook_preprocess(). It's fired for every theme preprocess (including page and block) – Clive May 27 '15 at 13:52

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.