简体   繁体   中英

Using “cycle” in smarty template system?

Here's my current code:

{foreach from=$items item=item name=utable}

{foreach from=$item.terms item=tmp name=titem}
<tr class="{cycle values="odd,even"}">

REMOVED UNNECESSARY CODE FROM HERE

{/foreach}
{/foreach}

The values odd and even are rotating correctly for the tr class.

However, the rotation doesn't restart with every new table. For example, I want the first tr of every table to have the class odd , but if the last table ended with odd , the next one keeps on starting with even .

Is there any way to make it the cycle stop at the end of each table and restart at the next?

You need to make use of reset attribute together with print .

Sample PHP data:

$data = [1 => [2,3,51], 2 => [5,6,1], 4 => [1,2,21]];
$smarty->assign('tables',$data);

Sample Smarty file:

<style>
    tr.odd {
        background: red;
    }
    tr.even {
        background: #fff;
    }
    table {
        margin: 50px 0;
    }
</style>


{foreach $tables as $table}
    {cycle values="" reset=true print=false}
    <table>
        {foreach $table as $row}
        <tr class="{cycle values="odd,even"}">
            <td>
                {$row}
                </td>
        {/foreach}
    </table>
{/foreach}

As alternative you can do it also this way:

{foreach $tables as $table}
    <table>
        {foreach $table as $row}
        {if $row@first}{assign var="reset" value=true}{/if}
        <tr class="{cycle values="odd,even" reset=$reset}">
            <td>
                {$row}
                </td>
         {assign var="reset" value=false}
        {/foreach}
    </table>
{/foreach}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM