Page 1 of 1

[SOLVED] Dynamic variable names values in page template loop

Posted: Mon Feb 02, 2015 5:33 pm
by applejack
Not sure if this is possible but in a page template I need to be able to re-create variable names within a smarty loop and pull out their values.

In a page template there are 20 content blocks using a naming convention speaker_name_1, speaker_name_2, speaker_name_3 all assigned to same named variables. In a section loop I need to be able to recreate the name and get the value. i.e. equivalent in PHP

Code: Select all

for ($i=1;$i<=20;$i++) {
    $block = 'speaker_name_' . $i;
    $block;
}
I thought this might work but it just gives the variable name as a string not the value.

Code: Select all

{section name=i start=1 loop=21}
	{assign var="var_name" value="speaker_name_"|cat:"`$smarty.section.i.index`"}
	{assign var="var_value" value=$var_name} 
	{$var_value}
{/section}

Re: Dynamic variable names and values in page template loop

Posted: Mon Feb 02, 2015 5:44 pm
by Jo Morg
You would need the variable variable syntax...
http://www.smarty.net/docs/en/language. ... iables.tpl

Code: Select all

$foo_{$bar}              // variable name containing other variable 
TBH I don't think that the PHP sample you pasted would work the way you expect, as its not a variable variable use...

Re: Dynamic variable names and values in page template loop

Posted: Mon Feb 02, 2015 6:32 pm
by applejack
Hi Jo

Many thanks that worked.

From what I know you can create page content blocks dynamically in a loop. Is that correct ?

Re: Dynamic variable names and values in page template loop

Posted: Mon Feb 02, 2015 6:38 pm
by Jo Morg
applejack wrote:From what I know you can create content block dynamically in a loop. Is that correct ?
No, not really. The template is parsed once before generating a backend editor page. So there's currently no way of recalculating how many blocks are needed triggered by a change on another custom content block, at least not with Core and Core modules.

Re: Dynamic variable names and values in page template loop

Posted: Mon Feb 02, 2015 6:41 pm
by applejack
Ok Thanks once again.

Solution to initial question is:-

Code: Select all

{section name=i start=1 loop=21}
	{$speaker_name_{$smarty.section.i.index}}	
{/section}