yii2yii2-advanced-appyii-modules

How to access css/js file for layout of a module in Yii2


I have a module named social with the directories like this :

frontend
-- modules
    -- social
        -- assets
            -- SocialAsset.php
        -- controllers
        -- views
            -- default
            -- layouts
                -- main.php
        -- web
            -- css
            -- js
            -- img
        Module.php

I want my module have an own layout. Because of that, i add file SocialAsset, main.php for layout, css, js and img. But, unfortunatelly i can't access my css/js/img files.

SocialAsset file :

<?php

namespace frontend\modules\social\assets;

use yii\web\AssetBundle;

class SocialAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $sourcePath = '@app/modules/social/web';
    public $css = [
        'css/social.css',
        'css/toolkit.css'
    ];
    public $js = [
        'js/jquery.min.js',
        'js/social.js',
        'js/toolkit.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

in main.php i use the SocialAssetfiles like this :

use frontend\modules\social\assets\SocialAsset;


SocialAsset::register($this);

Could someone to help me to solve this problem ?


Solution

  • You should only set sourcePath in your asset bundle :

    sourcePath specifies the root directory that contains the asset files in this bundle. This property should be set if the root directory is not Web accessible. Otherwise, you should set the basePath property and baseUrl, instead.

    This means you should simply remove $basePath and $baseUrl in your assset bundle, Yii will then publish your files.

    Read more : http://www.yiiframework.com/doc-2.0/guide-structure-assets.html