Register an asset in Yii2 for all views in a modul

2019-07-17 07:04发布

问题:

I have a module in Yii2 containing a lot of controllers, models and views.

How can I register an asset for all views, without register it in all view one by one?

回答1:

The module has init() method, you can use it for code that needs to be executed every time the module is accessed:

<?php

namespace frontend\modules\users;

use frontend\assets\UsersAsset;
use Yii;
use yii\base\Module as BaseModule;

class Module extends BaseModule
{
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'frontend\modules\users\controllers';

    /**
     * @inheritdoc
     */
    public function init()
    {
       UsersAsset::register(Yii::$app->view);       

       parent::init();            
    }
}

Don't forget to call parent implementation.