How to display a list of numbers and characters of the Alphabeth with a loop using Smarty

The usage of loops in Smarty and a lot of programming languages, make easy for the developer the writing process of templates. For example, imagine that you need to write some kind of Lexicon page and you need to show an organized/unorganized list with every character of the alphabet and the numbers that redirects to some URL where words that start with the mentioned character are shown on some other list.

Surely this becomes a boring task by writing everything manually with HTML:

<a href="/lexicon/0">0</a>
<a href="/lexicon/1">1</a>
<a href="/lexicon/2">2</a>
<a href="/lexicon/3">3</a>
<a href="/lexicon/4">4</a>
<a href="/lexicon/5">5</a>
<!-- .... -->
<a href="/lexicon/X">X</a>
<a href="/lexicon/Y">Y</a>
<a href="/lexicon/Z">Z</a>

No one wants that, really. Ignoring the fact that is pretty hard to maintain, the size of the files of your source code will differ hugely from good quality code. If you are using Smarty Templates in your project, you can easily generate the previous HTML with the help of a loop and the range modifiers.

Numeric list

For both lists, numeric and alphabetic, we will use the from and range modifiers in the foreach loop. These attributes work like a spread operator so to speak, following the ascending order in this case (as we are using the range from 0 to 9), smarty offers support as well with the descending order (9 to 0):

{* To display the list of numbers from 0 to *}
{foreach item=i from=0|@range:9}
        $i in this case contains the number in the order of the loop 
        e.g 1, 2, 3, 4 ...

        The output would be:
        <a href="/lexicon/0">0</a>
    <a href="/lexicon/{$i}">{$i}</a>

The previous snippet would be enought to display the numbers from 0 to 9 in our lexicon. Note that it isn't limited to 0 to 9 but any other number as well.

Alphabetic list

In the same way that we did with the range of numbers, Smarty is Smart enough to do the same with alphabetic characters, so if you want to display a list from A to Z, the following snippet should do the trick for you:

{* To display the list of characters from A to Z *}
{foreach item=i from='A'|@range:'Z'}
        $i in this case contains the character in the order of the loop 
        e.g A, B, C, D ...

        The output would be:
        <a href="/lexicon/A">A</a>
    <a href="/lexicon/{$i}">{$i}</a>

The same logic for the inverse order applies with characters too (from Z to A). In this case with the characters, our loop uses uppercase characters, so the output of our characters will be in uppercases (as expected). Doing the same with lowercase characters will display all the characters in lowercase.

Happy coding !

This could interest you

Become a more social person