Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Drupal - Provide a Custom HTML String Variable to a Node Type Template File

Category: 

To provide a custom php variable that contains an html string to your custom node type's template file, use some code sauce similar to this...

(Scroll down to the bottom for a Drupal 7 example)

Drupal 6

First in your theme's template.php file, add this (replace my_theme with the machine name of your theme):

/**
 * Implements template_preproccess_node().
 */
function my_theme_preprocess_node(&$variables) {
  if ($variables['node']->type == "my_custom_node_type") {
    $variables['my_custom_variable'] = "The Robots are Coming";
  }
}

Next up, in your custom content type's node template file (e.g. node-my_custom_node_type.tpl.php), add something like this:

<div class="node">
  <h1><?php print $title; ?></h1>
  <div><?php print $content; ?></div>
  <div><?php print $my_custom_variable; ?></div>
</div>

(The only code that we really care about is the one php line that prints out our custom variable, you can add that anywhere you'd like to your custom node type's template file.)

Now flush all of your caches in Drupal (or just the theme registry cache) and you'll be all set.

If you haven't yet created the template file for your node's custom content type, then you need to open up the node.tpl.php file that comes with your theme, then save a copy of it as node-my_custom_node_type.tpl.php (replacing my_custom_content_type with the machine name of your content type) inside the same directory as the node.tpl.php file. Then flush your site's caches and you will be ready to rock and roll, no time to fiddle!

Drupal 7

For Drupal 7, the code is exactly the same as above except for the naming convention used on your content type's node template file. In Drupal 7, you would use node--my_custom_node_type.tpl.php instead.

Add new comment