1

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
2

Your render array can return the #attached property:

$build = [
 '#title' => 'My Controller',
 '#plain_text' => 'Here is some text.'
];

$build['#attached']['library'][] = 'mycontroller/mylibrary';

return $build;

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/group/theme_render/8.2.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.