How to do SMARTY foreach loop to present array values from PHP?

SMARTY is a very good template engine that helps you decompose application view and model. If you want to create a SMARTY foreach loop, you need to have assigned array first. If you want only to present array values, then it can be a usual PHP array without special keys. But SMARTY foreach, same as foreach in PHP, can present keys for array items. The basic construction of foreach loop in smarty, together with PHP array assigment to present in view, you can see below: // In PHP: $array = new array( 'key1' => 'val1' , 'key2' => 'val2' ); $smarty->assign('someAssignedArray' , $array ); // In SMARTY: {foreach from=$someAssignedArray key=keyOfItem item=itemValue} The key of this item is: {$keyOfItem}<br> The value of this item is: {$itemValue}<br> {/foreach}As you can see, we have to have defined array first. Example above shows custom keyed array, but this array can also have standarized default keys like 0,1,2,3,4 etc. The first step is to assign our array to SMARTY variables, because SMARTY doesn't have access to global PHP scope in nice way. So we must define a custom name for this variable -in example above i named it 'someAssignedArray'. So, the array wich in PHP exeist as $array, will exist in smarty as $someAssignedArray.
Now, you can write a foreach loop in your tpl file. The basic atribute of SMARTY foreach tag is from. This attribute says, from wich array you want to pick up all items for iteration. Remeber that this variable must have a dollar sign at begining.
Second required parameter in this loop construction is item. Item refers to name of variable, wich will have a value from array inside the loop. Key attribute works in the same way - it will contains key for item value in single loop iteration. There is some important thing - remeber that you create a new SMARTY varaibles here, so do not use dollar sign.
Inside the foreach loop, you can access your array item value and key by varaible names you specified as foreach tag attributes, this time begininnig with a dollar sign.
Of course, if yours item value is an array, nothings stop you to provide a nested foreach loop, with new key and value variables. This is useful thing.
If you want to print your array in fastest way, only for debug etc. you can try to use print_r function in your SMARTY tpl file. I wrote some nice tutorial about using print_r in SMARTY, so check itd.
If you want to provide additional filtering when iterating over items, see my tutorial about modifiers here.

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP