|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
Kian987 Smarty Rookie
Joined: 13 Sep 2012 Posts: 12
|
Posted: Thu May 12, 2016 2:29 pm Post subject: Foreach initialized even when it's empty |
|
|
Hi,
I'm facing a very tricky issue because Smarty is doing nonsensical things.
Code: | {foreach from=$array item=item key=key}
{if $variable1[$variable2[$key]]}}
{$variable1[$variable2[$key]]}
{else}
{$somethingelse}
{/if}
{/foreach} |
I expect that when $array is empty Smarty doesn't even try to initialize the foreach but in reality it does and in fact this damned fatal error occurs:
Quote: | syntax error: unidentified token |
The reason is that $key is null obviously because $array is null too and so my if statement is broken because $key doesn't exist. Can you please explain me why Smarty initializes the foreach when it is empty? It's obvious that there's nothing to loop.
Anyway I can accept this "buggy" behaviour of the foreach but what I really can't understand is why the if condition gives me a fatal error. I mean I placed an if codition in front of my $variable1[$variable2[null]] exactly to test if the value exists so why doesn't it simply return false instead of a fatal error?
Any workaround? I really don't want to change my code because Smarty is doing something that shouldn't do.
Thank you. |
|
Back to top |
|
Kian987 Smarty Rookie
Joined: 13 Sep 2012 Posts: 12
|
Posted: Thu May 12, 2016 3:18 pm Post subject: |
|
|
I correct myself. There was a syntax error for real but the main question still remains: why Smarty initializes empty foreach loops? |
|
Back to top |
|
AnrDaemon Administrator
Joined: 03 Dec 2012 Posts: 1785
|
Posted: Thu May 12, 2016 10:36 pm Post subject: |
|
|
If foreach loop array variable is not set, PHP will throw an error you are describing.
It is normal.
If you want to avoid it, pass an empty array to the template. |
|
Back to top |
|
U.Tews Administrator
Joined: 22 Nov 2006 Posts: 5068 Location: Hamburg / Germany
|
Posted: Mon May 16, 2016 4:19 pm Post subject: |
|
|
I don't know which Smarty version you are using.
An empty or not assigned foreach loop array should not have produced any error.
But Smarty did perform unnecessary initialization of item and key variables.
The master branch version has been updated to avoid this |
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|