smarty
smarty copied to clipboard
reset($array)['key'] does not work as expected: SmartyCompilerException Syntax error in template - Unexpected "[", expected one of: "}"
The following code would be valid in PHP, but Smarty throws a SmartyCompilerException
{$a = ['2' => [ 'desc' => 'First entry\'s description' ] ]}
{reset($a)['desc']} {* should print "First entry's description" *}
Ideally, both Smarty and traditional array access syntax should be allowed. -- {reset($a).desc}
and {reset($a)['desc']}
According to {debug}
I'm using Smarty 4.1.0
@j-applese3d although I can see why you would expect this (as the Smarty syntax is obviously inspired on PHP syntax) there is nothing that requires Smarty to follow everything PHP does. Many PHP language constructs are not available in Smarty.
Okay. Thanks for the explanation. So, I suppose more generally, array access is only allowed directly on Smarty variables?
Do you think this would be something that could/should be added?
I suppose it's easy enough to make a modifier to do it, but of course built in support would be nicer :smile:
function smarty_modifier_a(array $ary, $index): mixed
{
return $ary[$index];
}
// then in Smarty:
{$a = ['2' => [ 'desc' => 'First entry\'s description' ] ]}
{reset($a)|a:desc}
I'm not sure what you mean exactly, but these all work perfectly:
$smarty = new Smarty();
$smarty->assign('myarr', ['a' => 'A', 'b' => 2, 0 => 15, 1 => [0 => 'TEST']]);
echo $smarty->display('string:
1: {$myarr.a}
2: {$myarr.b}
3: {$myarr["a"]}
4: {$myarr["b"]}
6: {$myarr[0]}
7: {$myarr[1][0]}
');
Output:
1: A
2: 2
3: A
4: 2
6: 15
7: TEST
Closed because of inactivity.