0

I have a module that conditionally includes a stylesheets using #attached on a render array it outputs. (By conditionally I'm meaning that sometimes the module adds the attached css, sometimes not; I'm not referring to conditional stylesheets as in "is it IE9".)

The render array the module outputs includes the following:

$output['#attached'] = array(
  'css' => array(
    'tiles-styles.css' => array(
      'data' => drupal_get_path('module', 'mymodule') . '/css/tiles-styles.css',
      'type' => 'file',
    ),
  ),
);

In my theme, I have css under a css/ directory. I want to override both these, but only when they are required.

It seems that by adding

css[tiles-styles.css][data] = 'tiles-styles.css'

to my theme.info file I can get my file included, and it overrides the module-provided one. However, doing this also includes this stylesheet on every page load, which is unnecessary.

Is there a way to override the stylesheet but only if the stylesheet was included in the first place?

1
  • I don't know for sure but I'd wonder if it was worthwhile if the alternative CSS is under a few hundred lines as unless you're running a really lean site because most people will be caching the CSS in their browser and having different style sheets will invalidate the cache. That said I can imagine lots of scenarios where you would want to do this, so just a thought really.
    – bloke_zero
    Commented Oct 6, 2015 at 9:10

1 Answer 1

0

You can do this by implementing hook_css_alter as follows:

/**
 * Implements hook_css_alter().
 */
function mytheme_css_alter(&$css) {
  if (isset($css['tiles-styles.css'])) {
    $css['tiles-styles.css']['data'] = drupal_get_path('theme', 'mytheme')
                                       . '/css/tiles-styles.css';
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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