smarty icon indicating copy to clipboard operation
smarty copied to clipboard

reset($array)['key'] does not work as expected: SmartyCompilerException Syntax error in template - Unexpected "[", expected one of: "}"

Open j-applese3d opened this issue 2 years ago • 3 comments

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 avatar Sep 14 '22 22:09 j-applese3d

@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.

wisskid avatar Sep 15 '22 07:09 wisskid

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}

j-applese3d avatar Sep 15 '22 16:09 j-applese3d

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

wisskid avatar Sep 22 '22 12:09 wisskid

Closed because of inactivity.

wisskid avatar Feb 18 '24 22:02 wisskid