Home » Smarty

Creating selection list, using foreach and section loop in Smarty

16 July 2008 1,155 views Popularity: 3% Share/Bookmark

email

In this article, I will be illustrating and explaining about foreach and section loop used in Smarty. I will be using these loops for creating a selection list.

We can create selection list from a custom Smarty function called ‘html_options’. html_options is a custom function that creates html option group with provided data. It takes care of which item(s) are selected by default as well. Required attributes are values and output, unless you use options instead.


Instead of html_options, we can also use loops to create the selection list. There are namely two loops in Smarty: 1) Section, and 2) Foreach

1) Template sections are used for looping over arrays of data. All section tags must be paired with /section tags. Required parameters are name and loop. The name of the section can be anything you like, made up of letters, numbers and underscores. Sections can be nested, and the nested section names must be unique from each other. The loop variable (usually an array of values) determines the number of times the section will loop. sectionelse is executed when there are no values in the loop variable.


2) foreach loops are an alternative to section loops. foreach is used to loop over a single associative array. The syntax for foreach is much easier than section, but as a tradeoff it can only be used for a single array. foreach tags must be paired with /foreach tags. Required parameters are from and item. foreach loops can be nested, and the nested foreach names must be unique from each other. The from variable (usually an array of values) determines the number of times foreach will loop. foreachelse is executed when there are no values in the from variable.


Download source code

Note: I have not included Smarty library files in this zip file. You can download the Smarty library files from http://smarty.php.net/download.php or directly from http://chapagain.googlecode.com/files/smarty.zip

Thank You.

Related posts:

  1. Pagination in PEAR and Smarty
  2. An Introduction to Smarty Template Engine
  3. Using jQuery & AJAX: Populate Selection List
  4. Templating in Smarty
  5. Using database in PEAR and Smarty
  6. PHP Javascript : Playing with multi-dimensional array
  7. Installing the Smarty Template Engine
  8. Magento: Authorize.net not displayed in Payment Information section while Checkout
  9. File Upload in PEAR and Smarty
  10. Magento: Product Edit Warning: Invalid argument supplied for foreach()
  • http://abhi-hiddentreasure.blogspot.com/ Abhi Khadka

    Looking great.. but some error in code.. please verify