Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I have a snippet of HTML that I've saved in my theme as mysnippet.inc. I'm using this code in template files (eg. node.tpl.php) to include it:

<?php include($directory."/includes/mysnippet.inc"); ?>

This is working fine, but the snippet also needs to access Drupal variable $node_url. So I tried to global it into my snippet:

<?php global $node_url ; ?>
<?php print $node_url; ?>

This doesn't work.

What would be the best way to achieve this? Should I be using template.php to create a variable containing my code snippet instead?

share|improve this question

2 Answers

up vote 0 down vote accepted

The best way to achieve this is to:

1. Create a custom theme function using hook_theme().

2. Implement a preprocessor in your template.php (you can also do it in a custom module). Here's a D.O. document describing how to do it. Assuming you want to preprocess the node.tpl.php template, a preprocessor that would be run regardless of what theme you are using would be called phptemplate_preprocess_node.

3. Inside your preprocessor, call the custom theme() function you created in step #1. Add the results of your theme function to the $variables array that are passed to your preprocessor. For example:

<?php
// In your template.php...
function phptemplate_preprocess_node($variables) {
  $variables['foo_bar'] = theme('my_theming_func', $params);
}

4. Now on node.tpl.php all you have to do is:

<?php
if(isset($foo_bar)):
  print $foo_bar;
endif;

I know that this sounds more difficult than what you where trying to do, however using PHP globals in Drupal and include_once in templates is highly discouraged.

share|improve this answer
Thanks for the detailed, clear answer. Am I right that step 1 (create custom theme function) would be done with a custom module? – pushka Dec 14 '11 at 8:11
@pushka Yes. You implement hook_theme() in your custom module. You substitute the word hook for the name of your module. So if your module is called pushka, your hook_theme() implementation would be written like function pushka_theme() { ... } – amateur barista Dec 14 '11 at 15:54

You can access the $variables array in your included file like this:

 // assuming you are viewing a node
 $node = $variables['node'];
 // the node is an object, so to display the url do
 echo drupal_get_path_alias('node/'.$node->nid);

To see what kind of data the $variables array contains do something like:

 echo '<pre>';
 print_r($variables);
 echo '</pre>';
share|improve this answer
This certainly works - thanks! – pushka Dec 14 '11 at 8:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.