How can I transform data into html

satya - Tuesday, July 19, 2011 2:22:47 PM

You can render any data using a template file

You can render any data using a template file:


theme_render_template($template_file, $vars);

This is a base drupal function.

You can get a path to a template file in your module as


$template_file = 
drupal_get_path(
   'module', 'your_module_name') . '/your-tempalte.tpl.php';

The $vars can be any data structure

satya - Tuesday, July 19, 2011 2:24:43 PM

Here is a sample template file


<table>
    <tr>
              <td><?php echo t('To');?>:</td>
              <td><?php echo $variable1;?></td>
            </tr>
              <td><?php echo render($form);?></td>
    </tr>
</table>

satya - Tuesday, July 19, 2011 2:30:43 PM

Here is a function that turns a set of taxonomy terms into html using a template


function test_function_convert_data_to_html_via_template()
{
      $vocabularies = taxonomy_vocabulary_get_names();
      $vid = $vocabularies['my_vocabulary']->vid;
      $terms = taxonomy_get_tree($vid, 0);
      $template_file = 
            drupal_get_path('module', 
              'Your_module') . '/your-template.tpl.php';
      dpm($terms);
      $vars['typeOfTermsArray'] = $terms;
      return theme_render_template($template_file, $vars);
}

satya - Tuesday, July 19, 2011 2:31:42 PM

Here is the corresponding template


<p>
Hello world. This demonstrates templates.
</p>
<?php foreach ($typeOfTermsArray as $term) : ?>
  <p>
  <?php echo $term->name; ?>
  </p>
<?php endforeach; ?>

satya - Tuesday, July 19, 2011 2:32:28 PM

Notice how the data is passed to the template

The data must be passed using an associative array. The name of the association becomes a variable name in the template file.

satya - Tuesday, July 19, 2011 2:34:32 PM

Hint: A theme function can pass a template instead of a theme function

In render arrays one can pass a theme function to render that data. One can also use a template file instead of a theme function.