How to add a suffix to every page title using events in Yii2

I’ve been using Yii and Yii2 for some years now, and I’ve been enjoying it pretty much. I’m delivering a new app, and I was wondering how to constantly add a suffix to every page title.

Well, while this can be easily achieved by tweaking the layout, as an exercise I decided to give a look at events. The idea is to attach an event after page rendering in order to tweak view’s title attribute.

So let’s see… One of the possible solution, according to the Bootstrapping documentation, is to use a custom component to be loaded into the

bootstrap

configuration key. Following this step, let’s create @app/components/Bootstrap.php file. The content must look like this:


<?php
/*
* Startup operations, keep fast!
* @link http://www.yiiframework.com/doc-2.0/guide-runtime-bootstrapping.html
*/
namespace app\components;

class Bootstrap extends \yii\base\Component {

public function init ()
{
    \Yii::$app->view->on(\yii\web\View::EVENT_AFTER_RENDER, function ($event) {
        if (\yii::$app->view->title != \Yii::$app->name)
            \yii::$app->view->title .= " · ".\Yii::$app->name;
        });
    }
}

Now that we have the code ready let’s tell Yii to load it. Edit config/web.php and in the bootstrap config key add ‘app\components\Bootstrap’ like this:

$config = [
    [...]
    'bootstrap' => ['log', 'app\components\Bootstrap'],
    [...]

So here we are. This little example will help you attach actions to Yii2 events.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.

Solve : *
4 + 20 =


Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.