Difference between e() and if-else

Hi!

I have a bunch of articles, each article can have one author. If the user does not choose an author, some default name is printed instead. I thought I would use simple e() function, so I wrote:

<?= e($author = $article->author()->toUser(), $author->name(), "Admin") ?>

It worked only in case every article had an author. If only one article did not have an author, I got error message: Call to a member function name() on null. For whatever reason, the condition in e() is evaluated to true (I think) even when the author is not chosen.

So instead of e() I tried something like this:

    <?php 
        if($author = $article->author()->toUser()) {
            echo "<p>".$author->name()."</p>";
        } else {
            echo "<p>Admin</p>";
        }
    ?>

And it worked. But I don´t know why. To me, these two pieces of code seems almost identical. Yet, they do not work the same way. :slight_smile:

See this answer: R() and e() bug

The parameters get evaluated during their processing, and that’s why the error is thrown. Try if that works: <?= $article->author()->toUser()->name() ?? "Admin">

Thanks texnixe, I think I understand it now.

Thank you Slinky. I tried your code, but it does not work. However, classic ternary operator does work, so I guess my problem is solved now.

Better don’t do this, without checking if you have a user object, calling the name() method will throw an error if the user doesn’t exist.

Correct:

<?= ($author = $article->author()->toUser())? $author->name() : "Admin" ?>

I try to keep my templates as clean as possible and would go for …

<?= $article->authorName(); ?>

There are two ways to achieve this:

1. Page model

to use it only for pages with “article” template

// site/models/article.php

class ArticlePage extends Page {
  public function authorName() {
    if ($author = $this->author()->toUser()) {
      return $author->name();
    }
    return 'Admin';
  }
}

or a …

2. Custom page method

to use it for all kind of pages

// site/plugins/myplugin/index.php

Kirby::plugin('myname/myplugin', [
  'pageMethods' => [
    'authorName' => function() {
      if ($author = $this->author()->toUser()) {
        return $author->name();
      }
      return 'Admin';
    }
  ]
]);