Jump to content

Smarty Variable Variables


richiman

Recommended Posts

Hello,

 

I have variables containing arrays that are named automatically: cate1 | cate2 | cate3 | and so on.

 

I need to use those vars in Smarty. The problem is that I cannot get it working with the official documentation.

 

cateX, where X is $i.

{section name=catdisp start=1 loop=$cattotal+1 step=1}
{assign var="i" value=$smarty.section.catdisp.index}

Iteration {$i} <br />

{$cate{$i}}

{/section}

 

Iteration works, but I cannot make the script output cate0. It does not even output: "Array".

 

Any help is greatly appreciated.

 

Regards,

Richi

 

 

Link to comment
https://forums.phpfreaks.com/topic/260588-smarty-variable-variables/
Share on other sites

Hello,

 

Are different arrays. {$cate1} works, but as I say, there can be up to 100 arrays: $cate100, or even more.

 

I've managed to get it working with a PHP block. I know it is not clean nor recommended, but that's the only thing I could get working in Smarty 2.x. Here's the code:

 

{assign var="name" value="cate"}
{php}
    $varname = $this->get_template_vars('name').$this->get_template_vars('i');
    $this->assign('result', $this->get_template_vars($varname));
{/php}

 

Then loop through result with a

{section name=result loop=$result}{/section}

 

Thanks for the help. I hope someone finds this post useful.

 

Regards,

Richi

Can you try doing the name as {$cate_{$i}}, as the manual uses ONLY examples separated by a _. I wouldn't think it would matter but I wonder if it does.

From manual:

$foo                    // normal variable

$foo_{$bar}              // variable name containing other variable

$foo_{$x+$y}            // variable name containing expressions

$foo_{$bar}_buh_{$blar}  // variable name with multiple segments

{$foo_{$x}}              // will output the variable $foo_1 if $x has a value of 1.

 

The last one is most like yours.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.