CMS Made Simple – Smarty Foreach Loops Made Simple, Part 2

CMS Made Simple Beyond the Basics – Do More with Foreach Loops

CMS Made Simple releases 1.11 (released July 28, 2012) and newer use the version 3 Smarty Template Engine. This introduced some new functionality and features to developers. Among the benefits is the ability to write a shortened version of the foreach loop.

The article, Smarty Foreach Loops Made Simple, provided a basic overview of how the foreach loop is used to access data inside of templates. For example, most of us are accustomed to working with this type of foreach loop in CMS Made Simple:
{foreach from=$items item='entry'} or {foreach from=$items key='key' item='entry'}

Now, we can write a foreach loop without named attributes and a bit more like the PHP syntax.
PHP:

foreach ($items as $entry) {
  echo "$entry";
}

CMS Made Simple with Smarty version 3:

{foreach $items as $entry}
{$entry}
{/foreach}

Properties are now accessed using a shortened method. For example, $entry@first, instead of, $smarty.foreach.foo.first.

{foreach $items as $entry}
{if $entry@first}Show first entry: {$entry}{/if}
{/foreach}

What else can we do with foreach loops inside of templates?

CMS Made Simple Foreach Loops

Show Only One Random Result

Using the PHP @array_rand method, a foreach loop looping through an indexed, associative, or multidimensional array can be written to show one random result. This can be useful to show a random image banner, announcement, or advert. The basic syntax is:

{assign var='randomresult' value=$array|@array_rand}
{foreach $array as $item} 
{if $item == $array.$randomresult}
<div>Random Result: {$item}</div>
{/if}
{/foreach}

To use in a multidimensional array, the foreach loop may need to use a $key and contain a nested loop.

{assign var='randomresult' value=$array|@array_rand} 
{foreach $array as $key => $items}
{if $items == $array.$randomresult}
<div>Random Result: {$key}: 
    {foreach $items as $item}
    {$item}
    {/foreach}
</div>
{/if}
{/foreach}

Assuming the array is something like the following:

$multidimensional = array(
  "Core Modules"=>array("News","Search","MicroTiny","Menu Manager"),
  "Addon Modules"=>array("Gallery","TinyMCE","CGCalendar","ListIt2")
);

To test, create a User Defined Tag (UDT) in the CMS using the previous code and this line:

$smarty->assign('array', $multidimensional);

Place the UDT into a content page with the foreach loop from above example (disable the WYSIWYG). There is an example of the results located on this foreach example page.

Split a Foreach in Half

There are times when the output of a module’s data needs to be displayed in two lists instead of one list. For example, to create a list of data split into two columns.

<ul>                        <ul>
<li>item 1</li>             <li>item 5</li>
<li>item 2</li>             <li>item 6</li>
<li>item 3</li>             <li>item 7</li>
<li>item 4</li>             </ul>
</ul>

To do this in a template or content page, a variable has to be assigned to count the items in the array.

{assign var='listsum' value=$items|@count}

Then, some math is used to divide the array into two halves and that result is assigned to a variable.

{math equation="x * y" x=$listsum y=.5 assign='itemscol'}

Now we can build the first unordered list. If the array contains an odd number of items, the variable $itemscol adds one more item to the first unordered list. This prevents the second list from having more items than the first list.  For example, if there are eleven items, it will distribute the first list with six items and the second list will have five items.  The PHP floor math function is rounding down the value of $itemscol, if needed.

<ul>
{foreach $items as $item}
{if $itemscol is odd}{assign var=itemscol value=$itemscol+1}{/if}
{if $item@iteration <= $itemscol|@floor}
<li>{$item->title}</li>
{/if}
{/foreach}
</ul>

The first foreach group prints all items that are less than the $itemscol variable. In this example, $itemscol begins with the value that is half of the total items in the array.  Let’s pretend the array has eleven items and therefore $itemscol has an initial value of 5.5.  Since it is an odd number, $itemscol is given the value of 6.5 and then rounded down to 6 from the PHP floor function.  This makes the first list with six items.

The second list is built with those items greater than the previous list.

<ul>
{foreach $items as $item}
{if $item@iteration > $itemscol|@floor}
<li>{$item->title}</li>
{/if}
{/foreach}
</ul>

The lists can be set next to each other on the web page using CSS floats or display: inline-block to create two columns. A working example of an array split in half using a foreach loop can be seen at this example page.

There are more ways to manipulate foreach loops using Smarty.  Documentation about the Smarty version 3 syntax for the foreach loop is available here.  Leave a comment below if you have questions about the foreach solutions in this article or have a question about a different foreach manipulation that you need for your project.


Looking for quality CMS Made Simple Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , , | Posted under CMS Made Simple | RSS 2.0

Author Spotlight

JohnnyB

JohnnyB

I've been a full-time front-end web developer for nine years working with design and marketing agencies and businesses located all over the USA. CMS Made Simple has been my go-to Content Management System since mid 2006.

Leave a Reply

Your email address will not be published. Required fields are marked *


4 − = 2

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>