问题
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.
来源:https://stackoverflow.com/questions/33656068/register-an-asset-in-yii2-for-all-views-in-a-module