Drupal 7 - Passing Page Level Variables to the Node Level

Today I had the need to pass variables typically only available at the page.tpl level to be accessible at the node.tpl level. My solution resulted in adding a preprocess_page(&$vars) to the template.php file.

In this specific situation I needed to know in the node.tpl if the sidebar_first region was populated with anything or not and if it was then it would determine which image style to use on a header image.

template.php

/**
 * Page preprocessor we use to check to see if there is the sidebar and then pass it on to the node level
 * @param $vars
 * @return unknown_type
 */
function comfortTech_preprocess_page(&$vars){
 //GB: We want the Node, if it's exists to know about the $sidebar_first and if it's loaded as it will determine what image style to use
    if(isset($vars["page"]["sidebar_first"])){
    	// add the flag to the node to say it's been set and there is only a single node to display    	
    	if(isset($vars["page"]["content"]["system_main"]["nodes"]) && count($vars["page"]["content"]["system_main"]["nodes"]) == 2){
    		$keys = array_keys($vars["page"]["content"]["system_main"]["nodes"]);
    		
    		// Set a new variable called sidebar_first equal to true on the node.tpl level
    		$vars["page"]["content"]["system_main"]["nodes"][$keys[0]]['#node']->sidebar_first = true;    		
    	}
    }
}

node.tpl

// set the image style variables needed for the theme call, checks to see if the $node->sidebar_first was set if it is then the sidebar is being displayed
	if(isset($node->sidebar_first)){
		$image_variable["style_name"] = 'header_image_half';
	}
	else {
		$image_variable["style_name"] = 'header_image_full';
	}
</code>
Blog Category: