Define dependencies between assets and views
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Define dependencies between assets and views


Create an instance of Assets for your views to use to request css and js files. Pass the object to any child view (layout view, page view, and any widget view) for them to request additional assets. Then, after rendering the html, use the object to insert the assets into the header (or footer) of the page.

Why an instance instead of a static collector class?

Static collector classes quickly fail when you need to keep track of multiple sets of asset requirements. If you are using Views to generate a PDF, you will want to create a new Assets instance in order to keep track of the assets the pdf will need to include.

Static collector classes also fail when your application executes sub-requests. There is no clean way to isolate the assets required in each request's response if the collector class is static. Giving your view an instance of Assets will make sure that when you render a view, the assets included in that view's header are always only the ones that the view and its sub-views requested.

Quick Usage

In the assets.php config file, define the groups of assets your application uses. These groups should be based on which assets a view might need so if a view uses jquery ui elements, you might want to create a jquery group that includes all the jquery files that a view might use.

return array
    'jquery' => array(
        // array($type, $url, $section, $weight),
        array('script', '', 'body'),
        array('script', '', 'body', 10),

Generally, it's good to have 2 sections for assets. I use body to indicate assets that need to be appended to the bottom of the file, and head to indicate assets that need to be placed in the <head> section.

In your code, you can mark an asset group for inclusion using Assets::group() or Assets::group().This is generally done in View constructors if using View Classes.

public function __construct(Assets $assets)
    $this->_assets = $assets;
    // This view requires jquery

At this point, you can use Assets::get() to retrieve all assets that were added by section.

$assets->get('body'); // Retrieves any asset in the `body` section within all required groups.