4

I am using basic pack of Yii2. I created a module named Admin and I want this module has its own layout. But I don't know where to put all its CSS files. Then, how to include them in layout.php.

My directory structure:

basic
-- module
  -- admin
    -- controllers
       -- DefaultController.php
    -- views
       -- default
       -- layouts
          -- main.php
          -- css
             -- style.css

In main.php, I use this code, but it doesn't work:

<?php $this->registerLinkTag([
    'rel'  => 'stylesheet',
    'href' => 'css/style.css',
]);
$this->head(); ?>

2 Answers 2

5

Create custom asset bundle class file here:

frontend/module/admin/assets/AdminAsset.php

It is important to initialize $sourcePath and $css variables properly. Here is an example:

use yii\web\AssetBundle;   

class AdminAsset extends AssetBundle {

    // The directory that contains the source asset files for this asset bundle
    public $sourcePath = '@app/module/admin/web';

    // List of CSS files that this bundle contains
    public $css = ['css/admin.css'];

}

Now you can register this AdminAsset bundle (in layout, view, etc.):

use frontend\module\admin\assets\AdminAsset;
AdminAsset::register($this);
Sign up to request clarification or add additional context in comments.

2 Comments

not able to register Admin. It shows me unable to find class Admin
Remove public $basePath = '@webroot'; and public $baseUrl = '@web'; if u use public $sourcePath
-1

Open the 'basic' folder. you will see a folder named assets.
Then open the assets folder and in the AppAsset.php file add your css

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        'css/main.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

2 Comments

This will add these css files to the whole project, right ? How can i add to just 1 module ?
So, you can just comment the bootstrap part i.e. public $depends = [ // 'yii\web\YiiAsset', //'yii\bootstrap\BootstrapAsset', ]; It will automatically select the file you need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.