When you have a region that needs to be styled differently depending on the number of blocks that are in that region or you need to know which one is the last it is useful to have a variable available to the block template which hold the number of blocks and the current block in a region.
This information is not available by default. Which positional information is available?
In theme.inc:
function template_preprocess(&$variables, $hook) { ... $variables['id'] = $count[$hook]++; ... } function template_preprocess_block(&$variables) { ... $variables['block_id'] = $block_counter[$variables['block']->region]++; ... }
The first preprocess function sets a general id over all regions. The block_id variable will have the block position within a region. With block_id you can add a class to the first block in a region by adding in the class part of the block div in block.tpl.php:
if ($block_id == 1) print 'first';
To be able to detect the last block or to be able to act upon the number of blocks we need the block count for a region. This is a number that is not available by default and we need to get. When setting up the page Drupal will call $blocks = theme('blocks', $region);. If not overridden this will call theme_blocks($region) which will call block_list($region) to get the list of blocks for that region. This last function caches its result and is called anyway to set up the blocks. So we can call it again in the preprocess function of our theme to get the total block count for a region.
function mytheme_preprocess_block(&$variables) { $variables['block_count'] = count(block_list($variables['block']->region)); }
In your block.tpl.php you can now add a class 'block-count-' . $block_count for example. And in your css you can predefine different styles for the different possibilities. This works in Drupal 6 and 7.
Comments
Denalisian
2 years ago ...
It was great information for me. Thanks for help.
Post new comment