2

I know that drupal_add_css is depreciated, and that we should use #attached instead to attach a css style sheet to a module.

I am trying to replace the following (which works):

drupal_add_css(drupal_get_path('module', 'mymodule') .'/mymodule.css');

with #attached. But haven't found exactly where and how to add it.

Here is my second attempt (it still does not work):

/**
 * Implementation of hook_block_view()
 */
function mymodule_block_view($delta = '') {
  if ('mymodule' == $delta) {
    $render = array();
    $list = mymodule_fetch_from_info();
    foreach ($list as $element) {
      $render[] = array(
        '#type' => 'markup',
        '#markup' => $element[0],
        '#weight' => $element[1],
      );
    }
    $blocks['subject'] = t('Mymodule');
    $blocks['content'] = $render;
    $blocks['#attached'] = array (
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/mymodule.css',
       ),
    );
    return $blocks;
  }
}
4

You cannot use #attached inside your hook_theme implementation. Instead, you should add it when you're building a render array:

$blocks['content'] = $render;
$blocks['content']['#attached'] = array (
  'css' => array(
    drupal_get_path('module', 'mymodule') . '/mymodule.css',
  ),
);

As kiamlaluno already pointed out in the comments, in your code example $blocks['content'] is the render array, so the #attached element must be part of that array.

1
  • $blocks is not a render array, but $blocks['content'] is.
    – apaderno
    Apr 18 '15 at 20:28

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.