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

Ok so I am writing a custom module and am trying to undestand how Drupal manages theming output.

I have registered my theme function, ie

mymodule_theme() {
    return array(
        'mylist' => 'templates/mylist-template',
        'arguments' => array('data'=>NULL)
    );
}

The mylist-template contains a HTML table with a heading row, such as:

<table>
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
    <?php print $rows; ?>
</table>

As you can see here I want to output x number of rows using another template file such as list-rows.tpl.php, ie:

<tr>
    <td>1</td>
    <td>My Name</td>
</tr>

How do I achieve this? At the moment I have a menu item with my table function, let's say:

 function mymodule_table() {
     $output = theme('list','');
     return $output;
 }

This works fine but im not sure how I would implement my rows

share|improve this question

migrated from stackoverflow.com Sep 23 '11 at 18:08

1 Answer

up vote 2 down vote accepted

You need to (properly) define two theme hooks. One for your table, and the second for your rows. Then, in the preprocess function for your table, you can call the row template for each row in your data array, something like:

function MODULE_theme() {
  return array(
    'mylist' => array('arguments' => array('data' => array())),
    'mylist_row' => array('arguments' => array('id' => NULL, 'name' => NULL)),
  );
}

function MODULE_preprocess_mylist(&$variables) {
  $rows = array();
  foreach ($variables['data'] as $item) {
    $rows[] = theme('mylist_row', $item['id'], $item['name']);
  }
}

If you want to display a nice and themed table, you don't need to implement your own theme hooks using templates, the table theme hook provided by core should be fine. It is a complete and flexible solution for most table output needs.

function MODULE_table() {
  $header = array(t('ID'), t('Name'));
  $rows = array(
    array(1, 'foo'),
    array(2, 'bar'),
    array(3, 'foobar'),
  );
  return theme('table', $header, $rows),
}
share|improve this answer

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.