Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Common Assets with Advanced Configuration

Tags:

php

assets

yii2

I would like to use Yii2's advanced configuration with separate frontend, backend, common and console applications. I've got many common assets, including stylesheets, js files, and fonts that will be used in both the frontend and backend applications. It only makes sense then to put those assets in an assets folder in common.

Then, my quandry starts. It seems that I need a separate AppAsset.php file to manage assets in the frontend and backend portions of the overall application because some things will be different between the two. (I'm not really sure whether to refer to frontend, backend, etc. as separate applications within an overarching something, or to call them sub-applications of a big overarching application.) Anyway, it appears that I will need two AppAsset managers. I will handle all file conversions (scss→css for example) and file compression myself, so I have no need to configure asset manager to do that.

Unfortunately, the documentation on AppAsset and asset bundles is not clear at all on how to include specific files or directories in a bundle. The only thing I see is how to specify destinations using the $css, $js, variables. For input directories, I only see a $sourcePath. Does that mean that I have to create a separate bundle (and $sourcePath) for every single javascript, css, image, etc. file. That's a whole lot of bundles! Surely there's some way to include multiple asset files in a single bundle. Can someone show me how?

like image 406
LarryTX Avatar asked Apr 21 '14 22:04

LarryTX


1 Answers

Well I believe the purpose of a "bundle" is to let you cherry-pick which files you want.

You don't need to make a different bundle for each individual file.

For instance, in my super simple custom AssetManager I have this:

namespace frontend\assets;
use yii\web\AssetBundle;
use yii\web\YiiAsset;

class CustomAsset extends AssetBundle{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/custom.css',
        'css/custom_modals.css'
    ];
}

Since the two CSS folders/files are located in the frontend-section of my project and the CustomAsset is located there too, when I register this AssetManager it will go through the $css array and add them to the header section. It does the same for the $js array that you would add if you needed to. Also, just remember, the files need to be in a web-accessible folder.

like image 149
Schwoebel Avatar answered Sep 24 '22 08:09

Schwoebel