We have a content type, Basic Page, where we may want to include 3rd party CSS such as Bootstrap. However, this 3rd party CSS may conflict with our custom theme, mytheme. On the Basic Page, we added a custom field of type Boolean, field_include_css, that a content editor can set to true if they want to use the Bootstrap CSS instead of mytheme.

How would we remove all the libraries added to the page that come from mytheme?

Here is what we tried, but did not work.

function mytheme_preprocess_page(&$variables) {
  $node = $variables['node']'
  // Basic page's machine name is page.
  if(is_object($node) && $node->getType() == 'page' && $node->field_include_css->value == '1') {

    // above line didn't work so we also tried these, but they failed too.
    $variables['page']['#attached']['library'] = '';
    $variables['#attached']['library'] = '';

Drupal has dedicated theme hook, hook_page_attachments_alter, for this scenario. Your theme can hook into it, check the rendered route (for your node type), and take action on the $page['#attached']['library'] render array accordingly:

function MYTHEME_page_attachments_alter(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!is_null($node) && $node->getType() == 'page') {
    //@TODO: remove the appropriate library items from $page['#attached']['library']
| improve this answer | |
  • 1
    using \Drupal::routeMatch()->getParameter('node') got me the node i needed and then i was able to do the validation similar to your if statement. – usernameabc Apr 1 '19 at 17:53

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.