PhpStorm and code completion for $this⁠-⁠>⁠template

7 years ago by David Grudl  

How to activate the code completion for $this->template in presenters in PhpStorm, NetBeans or any other IDE?

In source code of class Control you can find this annotation that describes type of property $this⁠-⁠>⁠template:

/**
 * @property-read Nette\Bridges\ApplicationLatte\Template|\stdClass $template
 */

The stdClass class in the annotation is a workaround for PhpStorm to get rid of alerts on “undefined fields”. The Nette\Bridges\ApplicationLatte\Template is default template's class name.

However, it is more interesting to create a own class with a real list of the variables that the template uses, including their types. It may look like this:

class ArticleTemplate extends Nette\Bridges\ApplicationLatte\Template
{
	/** @var string */
	public $lang;
	/** @var int */
	public $page;
	/** @var string[] */
	public $menu;
	/** @var Model\Page */
	public $article;
}

And then put own class name in the annotation of a specific presenter to be used instead default one:

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

From now on, the code completion is perfect:

Latte plugin now supports suggestions in the templates as well. Just add {templateType App\Presenters\ArticleTemplate} at the beginning of the template.

This post was updated on 2/2020