PhpStorm and code completion for $this->template

by David Grudl 3 months ago in Nette

How to get rid of PhpStorm alerts on “undefined fields” and activate the code completion for $this->template in presenters?

So how to change this view with the underlined abc and the empty pop-up window:

Into this?

Simply. Just add the following annotation to the presenter (for example to BasePresenter):

/**
 * @property-read \Nette\Bridges\ApplicationLatte\Template|\stdClass $template
 */
abstract class BasePresenter extends Nette\Application\UI\Presenter

Note: In the latest versions of Nette, this annotation will be directly in the code.

Template class

The stdClass class in the annotation is a workaround for PhpStorm, which otherwise treats all variables as undefined. However, it is more interesting to create a class with a real list of the variables that the template uses, including their types. It may look like this:

class ArticleTemplate
{
    /** @var string */
    public $lang;

    /** @var int */
    public $page;

    /** @var string[] */
    public $menu;

    /** @var Model\Page */
    public $article;
}

And then put it in the annotation of a specific presenter instead of stdClass:

/**
 * @property-read ArticleTemplate|\Nette\Bridges\ApplicationLatte\Template $template
 */
final class ArticlePresenter extends Nette\Application\UI\Presenter

From now on, the message is perfect:

We still have to solve the suggestion in the template. So far, Latte plugin can't do it, but once it can, it could use the same template class. For example, there could be a new macro {template App\Presenters\ArticleTemplate} that will pass the template class name.

Recent posts