Jump to content

Archived

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

richiman

Smarty Variable Variables

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

 

 

Share this post


Link to post
Share on other sites

It's been a while since I've used Smarty but I think this might work...

 

{$cate.$i}

Share this post


Link to post
Share on other sites

It's been a while since I've used Smarty but I think this might work...

 

{$cate.$i}

I think that would look for $cate[0], that's array syntax not concatenation.

Share this post


Link to post
Share on other sites

What you wrote looks correct. Are you saying you have (for example) 4 arrays with different names, or you have one array with those 4 keys

$arr['cate1'] vs $cate1

 

What happens if you manually write {$cate1}, does it work that way?

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

×
×
  • 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.