1

I am trying to render a block with a custom css with it. I have obtained a render array for the block and now I add to it:

$render_array['#attached']['css'] = array(
   base_path() . 'path/to/module/css/abcd.css',
);

return drupal_render($render_array);

The path to the css file is correct, I am able to access it in the browser. However, the css styles are not applied to the block. What are the proper steps to take now to debug this problem?

Thanks in advance!

Edit: I have tried out Option 1, this is the result of dpm($block) in in the hook_block_view.

subject (String, 15 characters ) Correct subject
content (Array, 2 elements)

  #markup (String, 45 characters ) <span class="testtest"> Red text </span>
  #attached (Array, 1 element)
    css (Array, 1 element)
        0 (String, 58 characters ) /path/to/css

And the contents in the css file:

.testtest {
  color: #C43C55;
} 

Could it be a site configuration? Thanks!

  • I managed to get it to work by including the css into the page where the block was to appear. Which I realised now is what Pushpinder suggested as the 2nd option. I'm not sure why adding the css into the page didn't help though. – cowman Jun 16 '14 at 3:19
0

You are saying, you have already rendered content array for the block and after that you are adding css to this block. If block array is already rendered then where you are applying this css because array is already rendered for you. Now you have two options here.

Option 1: Add custom CSS to your block It should be something like this.

function foo_block_view($delta = '')
{
  if($delta == 'foo_delta')
  {
    $block = array
    (
      'subject' => t('Foo title'),
      'content' => array
      (
        '#markup' => '<p>' . t('Lorem ipsum text.') . '</p>',
        '#attached' => array
        (
           'css' => array('path/to/my.css'),
        ),
      ),
    );
    return $block;
  }
}

Option 2: Add custom CSS to your page before this block rendered (Not a great option for your case).

$content = array();
$content['#attached']['css'] = array(
  $path . 'my.css' => array(
      'group' => CSS_AGGREGATE_THEME,
      'weight' => 999
    ),
  );
return $content;
  • Thanks for your answer. But I have tried out option 1 and it does not seem to be working. I will add in some details in my post above – cowman Jun 11 '14 at 4:30
  • you please share your block_view() function code. We need to understand how you are making this block rendered array and adding your css into this. – Pushpinder Rana Jun 11 '14 at 4:45

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.