Dynamic Variable Name In Smarty 2

Posted by in Technical

So I spent the last few days figuring out how to create dynamic variables or variables variable in Smarty 2. If you only have one value the variable name will be

{$form.firstname}

But I need it to be dynamic like :

{$form.firstname1}
{$form.firstname2}
etc...

We name the counter variable as $count. In Smarty 3 you can easily use

{$form.firstname_$count}

If we loop with section, the could will look like this :

{section name=count loop=$whatArrayToLoop}
	{$form.firstname_$count}
{/section}

But this thing is not working in Smarty 2. I try to use smarty 3, but when I refresh my browser there are too many errors that I don’t think worth debugging just so I can use dynamic variable. After quite frustrated for a while I found douglas radburn’s blog post that perfectly fit my needs. For above requirement, My code will look like

{section name=count loop=$whatArrayToLoop}
    assign var="firstnames" value="firstname`$smarty.section.count.index`"}
	{$form.$firstnames}
{/section}

What we do above is we create a temporary variables firstnames, give value to it by adding firstname (as string), and the count index. and then we use firstnames on our dynamic variable. Simple eh? 🙂