- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
Yii2 Asset Bundles & Asset Management
Introduction
Asset management in Yii2 helps developers efficiently manage JavaScript, CSS, images, and other frontend resources. Yii2 introduces the Asset Bundle concept, which allows grouping related assets and controlling their dependencies.
This tutorial covers:
- What Asset Bundles are
- How to create and register Asset Bundles
- Dependency Management in Asset Bundles
- Publishing assets
- Using Asset Bundles in Modules
- Customizing asset paths and versions
- Performance considerations
What is an Asset Bundle?
An Asset Bundle in Yii2 is a collection of frontend assets like CSS, JS, and images. These bundles are registered in views and automatically published to the web/assets
directory when requested.
Yii2 uses yii\web\AssetBundle
as the base class for defining an asset bundle.
Default Asset Bundles in Yii2
Yii2 provides several default asset bundles:
yii\web\YiiAsset
– Includes Yii's JavaScript frameworkyiiootstrap5\BootstrapAsset
– Loads Bootstrap 5 CSSyiiootstrap5\BootstrapPluginAsset
– Loads Bootstrap 5 JS
Creating an Asset Bundle
To create an Asset Bundle, extend yii\web\AssetBundle
.
Example: Creating AppAsset
Create assets/AppAsset.php
:
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/site.js',
];
public $depends = [
'yii\web\YiiAsset',
'yiiootstrap5\BootstrapAsset',
];
}
Explanation
$basePath
: The directory where assets are located.$baseUrl
: The URL path of the assets.$css
: List of CSS files.$js
: List of JavaScript files.$depends
: Other asset bundles this bundle depends on.
Registering Asset Bundles in Views
To include the AppAsset
bundle in a view file, register it like this:
use app\assets\AppAsset;
AppAsset::register($this);
This will include the CSS and JS files from AppAsset
in the HTML output.
Dependency Management
Dependencies ensure required CSS and JS files are loaded in the correct order.
For example, if your script requires jQuery, you should depend on yii\web\JqueryAsset
:
public $depends = [
'yii\web\JqueryAsset',
];
Yii will automatically include jQuery before your script.
Asset Publishing
Yii2 publishes assets when they are located outside the web root.
Example: Suppose your assets are inside @app/widgets/assets
, they will be copied to web/assets
when requested.
You can force publishing:
$this->registerAssetBundle(AppAsset::className(), yii\web\View::POS_HEAD);
Custom Publishing Options
You can customize how assets are published using publishOptions
:
public $publishOptions = [
'forceCopy' => false,
];
- When
forceCopy
istrue
: Assets will be re-published on every request, useful for development. - When
forceCopy
isfalse
: Assets are only published once, improving performance in production.
Asset Bundles in Modules
Each module can have its own Asset Bundle.
Example: Define ModuleAsset
in modules/admin/assets/ModuleAsset.php
:
namespace app\modules\admin\assets;
use yii\web\AssetBundle;
class ModuleAsset extends AssetBundle
{
public $sourcePath = '@app/modules/admin/assets';
public $css = ['admin.css'];
public $js = ['admin.js'];
public $depends = ['yii\web\YiiAsset'];
}
Register it in the module’s layout:
use app\modules\admin\assets\ModuleAsset;
ModuleAsset::register($this);
Using Separate Views & Layouts in Modules
To use custom views for a module:
\Yii::$app->view->theme = new \yii\base\Theme([
'pathMap' => ['@app/views' => '@app/modules/admin/views'],
]);
Customizing Asset Paths and Versions
To set versioning, use AssetManager::$appendTimestamp
in the application config:
'components' => [
'assetManager' => [
'appendTimestamp' => true,
],
]
This appends timestamps to asset URLs (site.css?v=1610000000
), forcing the browser to reload updated files.
For external assets:
public $js = [
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js',
];
You can also specify where scripts should be loaded using jsOptions
:
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
POS_HEAD
: Loads the script in the<head>
section.POS_BEGIN
: Loads the script at the beginning of<body>
.POS_END
: Loads the script at the end of<body>
(recommended for performance).
Performance Considerations
- Use
AssetManager::$appendTimestamp
to prevent caching issues. - Combine and minify assets using
AssetManager::bundles
. - Avoid
forceCopy = true
in production to prevent unnecessary re-publishing. - Load JS files at
POS_END
for better page load speed.
Conclusion
Yii2's Asset Management simplifies frontend asset handling, ensuring efficient loading and dependency management. Asset Bundles help organize and optimize JavaScript and CSS files, making the application modular and scalable.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Government Datasets from 50 Countries for Machine Learning Training
- 10 Awesome Data Science Blogs To Check Out
- Loan Default Prediction Project Using Machine Learning
- Big Data: The Future of Data-Driven Decision Making
- AI in Cybersecurity: The Future of Digital Protection
- What is YII? and How to Install it?
- Robotics & AI – How AI is Powering Modern Robotics
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Python Challenging Programming Exercises Part 3
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Datasets for analyze in Tableau
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset