5

I would like to know if it is possible to do something similar to a for cycle using Smarty 2.

I would like to have something like this:

<select>
{for $i from 1950 to 2000 }
   <option value="{$i}">{$i}</option>
{/for}
</select>

What function should I use, if any?

HappyDog
  • 1,230
  • 1
  • 18
  • 45
nunos
  • 20,479
  • 50
  • 119
  • 154

3 Answers3

6

You could use PHP's range function:

<select>
    {foreach item=i from=1950|@range:2000}
        <option value="{$i}">{$i}</option>
    {/foreach}
</select>
HappyDog
  • 1,230
  • 1
  • 18
  • 45
johnh
  • 133
  • 1
  • 5
6

Try {section} as it is described in the smarty docs

By the way: Check the {html_options} function: html_options docs

Roman
  • 5,651
  • 1
  • 30
  • 41
3

This is an old question and already has an accepted answer, but the answer was basically just a link. I have posted this as a more complete answer, to avoid future visitors having to trawl the docs to find the relevant example.


In Smarty 2, loops are achieved using the {section} tag, which covers quite a broad range of use-cases. To write the equivalent of a PHP for() loop, the following syntax is used:

<select>
{section name="i" start=1950 loop=2001}
   <option value="{$smarty.section.i.index}">{$smarty.section.i.index}</option>
{/section}
</select>

Note that the loop property refers to the number at which Smarty will break out of the loop, so it needs to be 1 higher than the final number you want to iterate over.


ADDENDUM: Although this is not directly relevant to the question (which is about Smarty 2), it is worth noting that Smarty 3 introduced a {for} tag, so you can now do the following, which is a lot simpler:

<select>
{for $i=1950 to 2000}
   <option value="{$i}">{$i}</option>
{/for}
</select>
HappyDog
  • 1,230
  • 1
  • 18
  • 45