Registering and Requiring CSS & JavaScript

Assets in Concrete CMS are new 5.7. They make it easy to define and group related CSS and JavaScript files, to ensure that the proper files are including on the proper pages, in the proper order. The Asset system even includes support asset versioning, minification and combination.

Registering an asset used by a custom block is easy. For example, let's say we want to include the Mediaelement.js library in our Custom Block. First, we make sure it's present in our block's directory (by copying it into application/blocks/audio_player/, for example.)

Then, we register the JavaScript and CSS files used by the library. This should be done in our block controller's on_start() method, which we may have to create.

public function on_start()
{
    $al = \Concrete\Core\Asset\AssetList::getInstance();
    $al->register(
        'javascript', 'mediaelement', 'blocks/audio/mediaelement/mediaelement-and-player.min.js',
        array('version' => '2.16.3', 'minify' => false, 'combine' => true)
    );
    $al->register(
        'css', 'mediaelement', 'blocks/audio/mediaelement/mediaelementplayer.min.css',
        array('version' => '2.16.3', 'minify' => false, 'combine' => true)
    );
}

Next, we group the asset into a single asset group.

$al->registerGroup('mediaelement', array(
    array('css', 'mediaelement'),
    array('javascript', 'jquery'),
    array('javascript', 'mediaelement')
));

Finally, we require the asset from within a registerViewAssets() method in our block controller:

public function registerViewAssets($outputContent = '')
{
    $this->requireAsset('mediaelement');
}

That's it! More information on assets can be found in the Asset Documentation, including additional parameters for the register() method.