Adding a custom block to the theme
This recipe details the steps involved in adding a block with custom content to the theme. Drupal blocks can either be declared using a module or, as we are doing here, added manually via the block administration interface.
Getting ready
For this recipe, we will be adding a simple welcome message in a custom block within a predetermined region. As with standard blocks, position matters!
How to do it...
The following procedure outlines the steps required to add a custom block to a theme:
Navigate to
admin/build/block
(Home | Administer | Site building | Blocks).Click on the Add block tab at the top of the page.
In the Block specific settings fieldset, type Welcome message in the Block description text field.
This description field comes in handy on the Block administration page when trying to differentiate between blocks with identical titles, or as is frequently the case, no titles.
Next, if the block requires a title to be displayed above its content, add one via the Block title textfield. In this case, we do not need one as we are just looking to display a welcome message.
Enter the following text into the Block body textarea: Welcome to Mysite. Enjoy your stay!.
Similar to most other textareas in Drupal, a linked Input format should be available to filter the content appropriately.
Finally, click on Save block to create the block.
How it works...
Just as with standard blocks, Drupal maintains a table named boxes
which tracks all custom blocks including their content and input format. Once a custom block is enabled, it is added to the blocks
table and tracked as if it was a standard block.
When created, a custom block appears in the block list and can be treated just like any other block. It can be dragged around different regions, have its visibility settings controlled, and so on. The following screenshot displays our newly created welcome block:
Tip
An easy way to identify custom blocks on the block management page is by their telltale delete links. Only custom blocks feature a delete option.
There's more...
Custom blocks are useful in rendering more than just simple text strings.
Doing more with custom blocks
Custom blocks can be very handy to not only add visible content, but also to execute short code snippets on specific pages, provided the appropriate input format has been selected. For example, we could embed some custom JavaScript required only for a few specific page nodes, by adding it to a custom block—equipped with a suitable input format—which is set to be displayed only with the aforementioned page nodes.
That said, if a more optimal solution is available—such as using a module to hold our code—then it should be pursued instead of inserting code into blocks and thereby into the database.