Do you usually come across the questions like, What isYii / Yii2? How to install it? Check out the blog written by SurajMalve:How To Install Yii2 framework- A Complete Step by Step Guide

In this tutorial, we are going to cover basic usage of Asset Bundles in Yii2 framework as well as how to add custom JavaScript and CSS scripts to a specific page of your web application.

What Is an Asset Bundle?

Well… I will say it is used to form a face of your web application as it represents a group of CSS and JavaScript files together that needs to be used / rendered across the website pages.

In technical language, Asset Bundles are PHP classes extending from \yii\web\AssetBundle.

Asset bundle makes it easy to group specific Scripts and CSS for specific pages,

Let’s take an example of Password Meter.

Defining an Asset Bundles / Creating an asset bundle

Let’s create a file named “PsmeterAsset.php” in ‘frontend/assets’ folder.


The above PsmeterAsset class specifies that the asset files are located under the @webroot directory which corresponds to the URL @web

If you are willing to put asset files in specific extension OR in bower package you can use @vendor/FILE_PATH OR @bower/FILE_PATH as Base Path respectively

 Integrating an Asset Bundle

After creation in order to integrate it with your web page register it in the view file.

Initiate asset bundle in your view file, as shown below:


That’s all, now you can see the result of above asset bundle in below image:


Believe me, Yii2 Asset bundle is pretty easy to manage.

Asset bundle helps a lot to re-use JavaScript and CSS in certain areas of a web application in an organized manner and reduces unnecessary loading of scripts on each page of a website.


1] Yii Framework 2.0 API Documentation

2] Defining Asset Bundle

3] Using Asset Bundle

POSTED IN: October 4, 2016 Ashwini Bhosale