In some cases you might want to adjust the default back end stylesheets or add additional stylesheets or JavaScript for your back end modules. As outlined in the asset management framework article, you can inject additional assets for the back end via the following global arrays:
Array | Description |
---|---|
$GLOBALS['TL_CSS'] | Additional stylesheets for the <head> . |
$GLOBALS['TL_JAVASCRIPT'] | Additional JavaScript files for the <head> . |
$GLOBALS['TL_MOOTOOLS'] | Additional HTML code at the end of the <body> . |
Adding additional entries to these arrays can be done in many ways. This guide will outline two general use cases, in order to give an idea what is possible.
Starting with version 4.11 global assets can now be added via the config/config.yaml
:
Additional back end settings
If you need assets globally in the back end, e.g. when customizing the back end
theme, then one way to ensure that your assets are inserted on every back end page
is to use a Symfony kernel event and then check for the Contao
back end scope there. The following example implements an event subscriber
for this purpose using the kernel.request
event in order to add a Font-Awesome
kit to the back end.
// src/EventSubscriber/KernelRequestSubscriber.php
namespace App\EventSubscriber;
use Contao\CoreBundle\Routing\ScopeMatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class KernelRequestSubscriber implements EventSubscriberInterface
{
protected $scopeMatcher;
public function __construct(ScopeMatcher $scopeMatcher)
{
$this->scopeMatcher = $scopeMatcher;
}
public static function getSubscribedEvents()
{
return [KernelEvents::REQUEST => 'onKernelRequest'];
}
public function onKernelRequest(RequestEvent $e): void
{
$request = $e->getRequest();
if ($this->scopeMatcher->isBackendRequest($request)) {
$GLOBALS['TL_JAVASCRIPT'][] = 'https://kit.fontawesome.com/xhcf1h83c6.js';
}
}
}
In other cases it might be sufficient to add additional assets only for a specific
DataContainer view, e.g. when you created a custom content element
and want to style its appearance in the back end. In that case you can also use
the onload
DCA callback for the specific DCA.
// src/EventListener/DataContainer/ContentOnLoadCallbackListener.php
namespace App\EventListener\DataContainer;
use Contao\CoreBundle\DependencyInjection\Attribute\AsCallback;
#[AsCallback(target: 'config.onload', table: 'tl_content')]
class ContentOnLoadCallbackListener
{
public function __invoke(): void
{
$GLOBALS['TL_CSS'][] = 'files/path/to/my.css';
}
}