0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What if there are 32 items? Will it be able to make 4 rows?
+1 I always thought the solution I had come up with was too 'wordy'. This is quicker to read.
It only makes a new row on the 9th item, so yes, it will make 4 rows and not 5.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.