18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Theming a <strong>Module</strong><br />

if (is_array($elements['#items'][$key]['data'])) {<br />

$elements['#items'][$key]['data'] =<br />

drupal_render($elements['#items'][$key]['data']);<br />

}<br />

}<br />

return $elements;<br />

}<br />

In our single_blog_item_list_child_render() function, we simply loop through<br />

all the #items, determine if they have an array in their data element and call<br />

drupal_render() on its contents.<br />

Attaching CSS to render arrays<br />

If you look at the screenshot of the first version, you can see that the default styling<br />

of our block is less then inspiring, so let's tweak that by giving our content some<br />

sensible default styling by adding a CSS stylesheet.<br />

Since version 5, <strong>Drupal</strong> has had a drupal_add_css() function to add CSS stylesheets<br />

to pages. What's new in <strong>Drupal</strong> 7 is that, due to <strong>Drupal</strong>'s block and page caching and<br />

the capabilities of hook_page_alter(), we now need to attach our stylesheet directly<br />

to the render element that we are creating. If we were to use drupal_add_css(), the<br />

stylesheet would not be cached with its block and it would also be considerably more<br />

difficult to alter the stylesheet if a hook_page_alter() implementation desired<br />

to (For example if it removed the block and wanted to remove the CSS too.)<br />

So instead of calling drupal_add_css() from within our<br />

single_blog_block_view() function, we add it to the returned render array:<br />

// Add a CSS file to style the block.<br />

$block['content']['#attached']['css'][] = drupal_get_path('module',<br />

'single_blog') . '/single-blog.css';<br />

We use drupal_get_path() to find the path to our module relative to the website<br />

root. The #attached array can contain a list of CSS files and JS files to attach to<br />

our render element. For JavaScript files, just append them to the js array via<br />

['#attached']['js'][].<br />

And here are the contents of our single-blog.css stylesheet:<br />

/* $Id$ */<br />

.block-single-blog .content ul {<br />

padding-left: 0; /* LTR */<br />

}<br />

[ 102 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!