Drupal – Pass Data To Template File

Probably most useful for passing large blocks of data that can be iterated over from within the template file. Using this method allows the developer to keep the application logic separate from the presentation layer. The data being passed in would most typically be an array.

1) Create the function that will generate the data block i.e.

function template_preprocess_my_form(&$variables) {
     $data = array("foo" => "bar", "bar" => "foo");
     $variables['template_data'] = $data;

The important part is to name your function appropriately so that it will hook the correct form. In this instance the form hook is my_form.

2) Modify hook_theme to accomodate the variable

function my_module_theme() {
    $theme = array(
    'my_form' => array(
            'arguments' => array('form' => NULL,
                                 'template_data' => NULL),
            'template' => 'my_form_template',
    return $theme;

Here it is important to ensure the array element key matches the variable that was added to the form’s variable array – in this case it is template_data

3) Access the variable you have created in the template file. The variable will available by adding the $ to the variable created in the steps above, in this case $template_data, and it can be used as a normal php variable, i.e.

 $values) :
     echo $template_data[$i]

Leave a Reply

Your email address will not be published. Required fields are marked *