tags:

views:

369

answers:

1

Variable assigned in my template is {$testVariable_123}, where 123 is auto generated and is also assigned to template as {$autoValue}

So in my template I want to get value of above variable.

{assign var="anotherValue" value="testVariable_"|cat:$autoValue}

So if I print {$anotherValue} instead of value I get string 'testVariable_123'

Any help appreciated...

A: 

You need to create a variable whose value is {$testVariable_123}
Then you can call {eval} on it.

The problem is, I couldn't find a way to do this in a good manner.
Everything that looks reasonably good doesn't work and the options that work are ugly.

Maybe you'd consider some changes in your application design?

Here's what I managed to get working:

# file.php:

  $smarty->assign("autoValue", 123);
  $smarty->assign("testVariable_123", "foo");

  //Option 1
  $smarty->assign("anotherValue", "{\$testVariable_123}");
  //Option 2
  $smarty->assign("rb", '}'); // Hack to get the right bracket } withou Smarty parsing it.
  //Option 3
  $smarty->assign("mask", '{$testVariable_%s}'); // pass the full string_format "mask" directly from PHP

# file.tpl

1) Uses the $anotherValue from PHP:
Plain: {$anotherValue}
Evaled: {eval var=$anotherValue}

2) Build the string on Smarty itself:
{assign var="yetAnotherValue" value=$autoValue|string_format:"{\$testVariable_%s$rb"}
Plain: {$yetAnotherValue}
Evaled: {eval var=$yetAnotherValue}

3) Build the string using the mask from php:
{assign var="enoughOfValue" value=$autoValue|string_format:$mask}
Plain: {$enoughOfValue}
Evaled: {eval var=$enoughOfValue}

Mostly, the problem is that Smarty won't ignore a closing bracket } or a $variable even if it's in the middle of a string. Escaping with \ doesn't work neither.

If you try:

{assign var="yetAnotherValue" value="{\$testVariable_$autoValue}"}

it will ignore the "} at the end and consider the Smarty statement as:

{assign var="yetAnotherValue" value="{\$testVariable_$autoValue}

and it will evaluate the $testVariable even tho it was supposed to be escaped.
So we will end up with {\123 as the value :(

Everything I tried ended up stumbling on that issue. If you find a better way, please, make sure you share it here :)

Carlos Lima
Thanks a lot. I know it's complicated.. :(I changed my logic in my application.
Kurund Jalmi
Cool! I'm happy to help. At least it was fun to figure out an (ugly) solution. :)
Carlos Lima