Search code examples
phpsmarty

How to use Variable variables in Smarty?


I want to use variable variables in smarty. I know that we can use it in PHP. But I am unable to find any way to achieve the same in Smarty template file. Consider the below scenario.

I have multiple variables which I pass from PHP file to Smarty tpl file. All these variables name have some similar pattern. e.g. $test_1, $test_2, $test_3 and so on.

This is how, actually I am trying to achieve it. Here, $COUNTER represents 1, 2, 3....

 {$SELECTED_VALUE = "test_{$COUNTER}"}
 {$$SELECTED_VALUE|@print_r}

But when I try to print it out, it gives me error

Syntax Error in template "test.tpl" on line 127 "{$$SELECTED_VALUE|@print_r}" - Unexpected "$", expected one of: "{" , "identifier"

Now, in PHP, I can get the values of these variables using double $$ symbols. But I am unable to find any way to achieve the same in a smarty tpl file.

I have gone through these links, but couldn't understand anything out of it.

Variable Variable in Smarty Templates

Dynamics variables in smarty in loop

Kindly guide me here, if it is possible.


Solution

  • Ok, it seems that I have found the solution. As I have mentioned above, I have these dynamically created and assigned $test_1, $test_2, $test_3,.... to smarty tpl file. So to use these variables dynamically, I have taken followed approach.

    {for $counter=1 to $total}
          {$test_{$counter}}
     {/for}
    

    Thanks for help.