How to automatically prepend title in Yii2 application?

Click read more to check gist code.

  1. Create components directory and add Controller.php this will be our intermediary controller to add new functionalities.
  2. Extend your controllers with our new one.
  3. Add titleSeparator to params.php.
This is how it looks with title in view file.

Check my gist for details:


File: Controller.php
--------------------

view->on('afterRender', function($event) 
        {
            if(!empty(Yii::$app->view->title)) 
            {
                Yii::$app->view->title = Yii::$app->name . Yii::$app->params['titleSeparator'] . Yii::$app->view->title;
            } 
            else 
            {
                Yii::$app->view->title = Yii::$app->name;
            }
        });
    }
}

File: index.php
---------------

title = 'test';
?>

File: params.php
----------------

 'admin@example.com',
    'titleSeparator' => ' – ',
];

File: SiteController.php
------------------------

render('index');
    }
}