ReynierPM ReynierPM - 2 months ago 16
Smarty Question

Append $index to the end of the string in Smarty3

I have the following HTML code:

<input type="text"
name="line_item[hotel_info][{{$index}}][second_last_name_{{$index}}]"
value="{{$PREVIOUS_REQUEST.hotel_info.$index.second_last_name_$index}}"
>


What's the right way to append
$index
to the string being passed to the value? This
$PREVIOUS_REQUEST.hotel_info.$index.second_last_name_$index
is failing since Smarty doesn't like the
_$index
at the end of the string. Any help?

UPDATE: using
cat
:

I have tried using
cat
modifiers but still not working:

{{$PREVIOUS_REQUEST.hotel_info.$index.hotel_name_|cat:$index}}


Return
0
which is the value of
$index
but I need the value stored in the var.

Answer

Looks like you will need to use an intermediate variable:

{assign "sln" "second_last_name_$index"}
value="{{$PREVIOUS_REQUEST.hotel_info.$index.$sln}}"

Example:

$PREVIOUS_REQUEST = [ 'hotel_info' => [
    0 => [ 'second_last_name_0' => 'foo' ],
    1 => [ 'second_last_name_1' => 'bar' ],
]];

$smarty = new \Smarty;
$smarty->assign('PREVIOUS_REQUEST', $PREVIOUS_REQUEST);
$smarty->assign('index', 0);
$smarty->display(<<<'EOTPL'
string:
{assign "sln" "second_last_name_$index"}
index="{{$index}}"
index="{{$sln}}"
value="{{$PREVIOUS_REQUEST.hotel_info.$index.$sln}}"

EOTPL
);

Outputs:

index="0"
index="second_last_name_0"
value="foo"