Welcome Guest, Not a member yet? Register   Sign In
Creating a Smarty Cycle like function.
#1

[eluser]Bramme[/eluser]
Hey all

I'm trying to create a simple cycle function like smarty has. This function loops through a given number of values. I'm trying to do something similar: I'm trying to make a zebrastripe generator: even rows get a class, uneven rows get nothing.

The function looks like this at the moment:
Code:
function zebra_stripe($class = 'zebra', $start_at_zero = FALSE)
{
    $ci =& get_instance();
    if ($ci->session->userdata('zebra_counter') === FALSE)
    {
        $start = $start_at_zero ? 0 : 1;
        $ci->session->set_userdata(array('zebra_counter' => $start));
    }
    
    $counter = $ci->session->userdata('zebra_counter');
    
    $return = fmod($counter, 2) == 0 ? " $class" : "";
    
    $counter++;
    $ci->session->set_userdata(array('zebra_counter' => $counter));
    
    return $return;
}
As you can see, this uses a session variable to store a counter. With every row the counter goes up. Some basic math checks if the counter is even or not.

Though this has a flaw: you need a reset function too with every page load. Else, when you have an uneven amount of rows, the striping will alternate every page refresh (since the session remains...)


I've been looking at how Smarty does it, but I can't seem to figure it out. Anybody got any suggestions on how to make this better/work without sessions? Or maybe have it reset automatically (without using hooks or smth that call the reset function at the end of the page...)
#2

[eluser]Johan André[/eluser]
Load the string-helper and do (in view):

Code:
<table>
  <tr class="&lt;?=alternator('odd', 'even');?&gt;">
    <td>A table cell</td>
  </tr>
</table>
#3

[eluser]Bramme[/eluser]
stupid me, thinking this hadn't been implemented yet. :p




Theme © iAndrew 2016 - Forum software by © MyBB