How do I manage assets in Yii2?

后端 未结 4 745
你的背包
你的背包 2021-02-05 05:59

For example, I created a new page, and I\'d like to use, for example, backbone.js, custom css file and some collection of images. Where should I declare all this stuff in Yii2?

相关标签:
4条回答
  • 2021-02-05 06:32

    At first, you should create SomeAsset class in your app/assets/ folder with your new js and css files. You can extend your AppAsset overloading its properties.

    Next use this in SomeController

    use Yii;
    use app\assets\SomeAsset;
    

    and in actionSome like this:

    SomeAsset::register(Yii::$app->view);
    
    0 讨论(0)
  • 2021-02-05 06:36

    It took me a while to figure it out, but below is the relevant part of the Yii2 source code

    if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) {
        list ($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions);
    }
    

    So Yii2 will publish assets only if $sourcePath is set, and $basePath and $baseUrl are not set(!). The latter tripped me up, and it looks like the same goes for you.

    So I have this AppAsset, which duly publishes

    use yii\web\AssetBundle;
    
    
    class AppAsset extends AssetBundle
    {
    public $sourcePath = '@app/assets/app';
    
    public $css = [
        'css/openbook.css',
        'fontello/css/fontello.css',
        'fontello/css/animation.css'
    ];
    public $js = [
        'js/plug.openbook.js',
        'js/plug.interpret.js',
        'js/plug.drop.message.js'
    ];
    public $depends = [
       // 'yii\web\YiiAsset', 
       // 'yii\bootstrap\BootstrapAsset',
    ];
    } 
    

    Of course, I have in the main layout

    use frontend\assets\AppAsset;
    ...
    AppAsset::register($this);
    
    0 讨论(0)
  • 2021-02-05 06:41

    From personal experience, assets are one of the parts of Yii that I found extremely frustrating.

    It is hard to reliably find out where the file is going to be and the switching back and forth with debug mode on and off will create further frustration.

    I suggest scrapping the asset handling and just keep all your JS files in a folder, then it can be included like this:

    Yii::app()->clientScript->registerScriptFile('/js/jquery.jeditable.mini.js');
    
    0 讨论(0)
  • 2021-02-05 06:49

    to use this AppAsset or any other you should register it in the view

    use app\assets\AppAsset;
    AppAsset::register($this);
    
    0 讨论(0)
提交回复
热议问题