Skip to content
Derek Jones edited this page Jul 5, 2012 · 15 revisions

Category:Views

Community: Please feel free to add other methods :-)

Zebra tables is a term used to describe tables that have alternating row colours:

[img]http://alistapart.com/d/stripedtables/itunes.png[/img]

This effect can be achieved using various methods, both server and client-side using PHP and CSS/Javascript.

Basic method

CSS

.tr1 td{ background:#F4B624; color:#000; }
.tr2 td{ background:#FFFFFF; color:#000; }

View

Make sure the string helper is loaded. It contains a function called alternator(), which is exactly what we need here. This function allows two or more items to be alternated between when cycling through a loop.

<?php foreach ($result as $row) { ?>

<tr class="tr&lt;?php echo alternator('1', '2') ?&gt;">
  <td>&lt;?php echo $row->name ?&gt;</td>
  ...
  <td>&lt;?php echo $row->descriptions ?&gt;</td>
</tr>

&lt;?php } ?&gt;

Output

<tr class="tr1">
  <td>Foo</td>
  ...
</tr>

<tr class="tr2">
  <td>Bar</td>
  ...
</tr>

Table Class Method

This method uses CodeIgniter's built-in table class library. First, build an array with the data for the table:

$table_data=array(
    array('Number in Stock','Item Name'),
    array('34','Boxes'),
    array('23','Pens'),
    array('98','Sheets of Paper'),
    array('12','Zebras')
);

Then build an array with some table settings:

$table_setup=array(
    'table_open' => '<table class="zebraTable">',
    'row_start' => '<tr class="rowOdd">',
    'row_alt_start' => '<tr class="rowEven">'
);

This sets an opening class for all your odd rows, and all your even rows, and cleans up the table opening tag. Only a class is really needed, if you're going for XHTML.

Build the table into a variable to pass to your View:

$this->table->set_template($table_settings); //apply the settings
$data['table'] = $this->table->generate($this->foo->getFoo()); //build the html output and stick in our data array
$this->load->view('tableview',$data);

Use the following (or similar!) styles in whichever stylesheet you wish to use:

.zebraTable tr {
    background-color:#FFFFFF;
}
.zebraTable .rowEven {
    background-color:#DDDDDD;
}

The resulting table html code is something similar to:

<table class="zebraTable">
<tr>
<th>Number in Stock</th><th>Item Name</th></tr>
<tr class="rowOdd">
<td>34</td><td>Boxes</td></tr>
<tr class="rowEven">
<td>23</td><td>Pens</td></tr>

<tr class="rowOdd">
<td>98</td><td>Sheets of Paper</td></tr>
<tr class="rowEven">
<td>12</td><td>Zebras</td></tr>
</table>

Good luck, and have fun!

Clone this wiki locally