开发者

Smarty: Outputting Rows Based on # of Items in Array

I am using Smarty to output an array to an HTML table. I want each row of the table to 开发者_开发知识库have no more than 8 items in it. If the array has more than 8 items then the code would make a new row for the overflowing items.

How can I do this? Is this clear?


It's been a long time since I've used Smarty, but you should be able to do this like this:

<tr>
{foreach from=$items key=myId item=i name=foo}
  {if $smarty.foreach.foo.index % 8 == 0 && $smarty.foreach.foo.index > 0 }
     </tr><tr>
  {/if}
  <td>{$i.label}</td>
{/foreach}
</tr>

The modulus operator only returns 0 if the index is dividable by 8, So before every 9th item it adds a new row. We don't want this for the first item to happend so let's check that as well.


Here's how I did it in the past:

<table>
    {foreach from=$array item='array_item' name='array_items'}
        {if $smarty.foreach.array_items.first}
            {* first item - start of all the rows *}
            <tr><td>{$array_item}</td>
        {elseif $smarty.foreach.array_items.index % 8 == 0}
            {* 8 items added to row - start new row *}
            </tr><tr><td>{$array_item}</td>
        {elseif $smarty.foreach.array_items.last}
            {* last item - end the row (or add logic to fill out row with empty cells if needed) *}
            <td>{$array_item}</td></tr>
        {else}
            {* normal item - add cell *}
            <td>{$array_item}</td>
        {/if}
    {/foreach}
</table>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜