I have a custom module that creates its own page and displays some stuff. I have some CSS and JS to add, and I'm using a library. The CSS and JS are being added, but to every page on the site. Can someone tell me how to restrict them to this page only?
The docs say "But what matters most is that we don't decide whether to attach a library based on which page we're on (i.e. which URL or route), but based on which things are visible on the page..." So, if that really is what matters most, then maybe I'm going about this all wrong?
MycontrollerController.php
<?php
namespace Drupal\mycontroller\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Returns responses for mycontroller routes.
*/
class MycontrollerController extends ControllerBase {
public function content() {
return [
'#title' => 'My Controller',
'#plain_text' => 'Here is some text.'
];
}
}
mycontroller.info.yml
name: My Controller
description: It's a very nice controller
type: module
core: 8.x
mycontroller.routing.yml
mycontroller:
path: '/mycontroller'
defaults:
_title: 'Mycontroller'
_controller: '\Drupal\mycontroller\Controller\MycontrollerController::content'
requirements:
_permission: 'access content'
mycontroller.libraries.yml
mylibrary:
version: 1.x
css:
layout:
css/mycontroller-layout.css: {}
js:
js/mycontroller.js: {}
mycontroller.module
<?php
function mycontroller_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'mycontroller/mylibrary';
}
My directory structure...
mycontroller
|-- css
| `-- mycontroller-layout.css
|
|-- js
| `-- mycontroller.js
|
|-- mycontroller.info.yml
|-- mycontroller.libraries.yml
|-- mycontroller.module
|-- mycontroller.routing.yml
`-- src
`-- Controller
`-- MycontrollerController.php