How do I add

Add "first" and "last" classes on blocks

Last modified: August 23, 2009 - 15:25

Sometimes, the first or last block in a region needs to be styled different than the rest. To get 'first' and 'last' classes on the first and last block in a region, you need to override two theme functions: theme_block() and theme_blocks().

1) Override theme_blocks()

<?php
function phptemplate_blocks($region) {
 
$output = '';

  if (
$list = block_list($region)) {
   
$blockcounter = 1; // there is at least one block in this region
   
foreach ($list as $key => $block) {
     
// $key == <i>module</i>_<i>delta</i>
     
$block->extraclass = ''; // add the 'extracclass' key to the $block object
     
if ($blockcounter == 1){ // is this the first block in this region?
       
$block->extraclass .= ' first'
      }
      if (
$blockcounter == count($list)){ // is this the last block in this region?
       
$block->extraclass .= ' last';
      }
     
$output .= theme('block', $block);
     
$blockcounter++;
    }
  }

 
// Add any content assigned to this region through drupal_set_content() calls.
 
$output .= drupal_get_content($region);

  return
$output;
}
?>

2) Override theme_block()

<?php
function phptemplate_block($block) {
$output = "module $block->extraclass\" id=\"block-$block->module-$block->delta\">\n"; // in this line, the extraclass value is added as class

Add "first" and "last" classes on list view LI's

Last modified: August 23, 2009 - 15:34

Much like HowTo: Have "first" and "last" classes on menu blocks sometimes you need to be able to address the first and last elements of lists, this howto allows you to have that for your LI's.

The processing of lists is done by function theme_item_list($items = array(), $title = NULL, $type = 'ul', $attributes = NULL) which can be overridden in template.php. It only takes a few small changes to get this to work (adding $item_key to the foreach and checking it against count and 0 to determine if to apply the class).

Paste the code below into your template.php and you're done.

<?php
function phptemplate_item_list($items = array(), $title = NULL, $type = 'ul', $attributes = NULL) {
$output = '';
if (isset($title)) {
$output .= '

'. $title .'

';
}

if (!empty($items)) {
$output .= "<$type" . drupal_attributes($attributes) . '>';
foreach ($items as $item_key=>$item) {
$attributes = array();
$children = array();
if (is_array($item)) {
foreach ($item as $key => $value) {
if ($key == 'data') {
$data = $value;
}
elseif ($key == 'children') {
$children = $value;
}
else {

Syndicate content
 
 

Drupal is a registered trademark of Dries Buytaert.