How to add template identifier in Yii2 HTML output

Sometimes it’s nice to know which template is currently rendered, just by looking into HTML source. It saves a lot of time if your application is really big.

Example of my code output in the HTML source view.

To add such behaviour to your app simply edit your Yii2 config file (in my case it’s config/web.php), it is located in components section:

File: web.php

        'view' => [
            'on afterRender' => function ($event) {
                // Check if this is not a layout file
                if( preg_match( '/layouts/', $event->viewFile ) == 0 ) {
                     *  Add template info.

                    /** @var $event yii\base\ViewEvent */
                    $event->output = "\n" . $event->output . "\n";