Ecco() executes option even if false

Hi Kirby-Gurus,
I am using the ecco (e) function a lot like and noticed that the functions in the cases are executed even if the condition for them is not met:

function foo() {
   echo 'bar';
}

e(false, foo());

// => echoes 'bar'

Of course in this example I could easily use return values to prevent this snippet from outputting bar but I am not able to prevent errors in examples like this, where the $page-element does not have any images assigned:

e($page->images()->isNotEmpty(), $page->images()->first()->url())

Maybe this is just the desired behavior of ecco or my PHP knowledge is too sparse, but it would be nice to hear your opinion!

(Btw I know how to solve this error with an if-statement. I’m just curious how to solve it with ecco and if these side-effects couldn’t be avoided.

Dennis

Yes, you cannot use ecco() or e() in all situations. It’s ok for empty fields, but in your case, because the options are rendered before the evaluation, the call to the first() method is on a non-existing object, which will result in an error.

OK, thanks for the fast reply!

Is just vaguely remember from another programming language that function parameters could be marked as “Don’t execute until I say” which would be a great fit for ecco if something like this is possible in php, too.

There’s another issue here: isNotEmpty() is a field method, so it cannot be used to check if the image collection is empty.

Edit: if you need a shortcut to an if statement, you can use the ternary operator:

<?= $page->hasImages()? $page->images()->first()->url():''; ?>

I totally forgot the ternary operator. Thank you :slight_smile: