Search code examples
phpsmartysmarty3

Switch and case with Smarty templates?


I’m new to smarty. I’m trying to use switch and case function with smarty. This is the php code I use

$i=1;
while ($row = mysqli_fetch_array($sql)){

    switch($i%8){

            case 1:
            case 2:
                //DO Something Here
            break;
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 0:
                //DO Something Else Here
            break;
        }
    $i++;

    }

My question is how do i apply this code to Smarty? Appreciate your time.


Solution

  • I'm not sure replicating in Smarty is the best idea. The concept of Smarty is to keep logic like this inside your controller. Furthermore, you would have to fully raw translate the data to Smarty to do this within Smarty. In other words, you'd have to loop over the data twice. Instead, I'd build the data into a structure like an array and pass that into Smarty. Than you can use a simple {foreach} in smarty to loop over the data.

    $data = array();
    $i=1;
    while ($row = mysqli_fetch_array($sql)){
    
        switch($i%8){
    
                case 1:
                case 2:
                    $data[$i][] = $row; //DO Something Here
                break;
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 0:
                    $data[$i][] = $row; //DO Something Else Here
                break;
            }
        $i++;
    
        }
    $smarty->assign('data', $data);