Drupal – Introduction to Drupal Theming @ 3

Update @ 20130303: For Drupal 7, please refer to the following post.
Drupal 7 – Create your own theme function on your custom block

 

Previous related articles
Drupal – Introduction to Drupal Theming @ 1
Drupal – Introduction to Drupal Theming @ 2

So we could now use a .tpl.php for our customized content. The last thing i would like to mention is about the preprocess function.

Suppose i want to load a node content on the .tpl.php, we can either include the node as an arguments when calling the theme function like.

...
// pass the 1st node to the .tpl.php
$block['content'] = theme('eureka', node_load(1));
...

 

Again, it is not a good practice. Think about if you have more then 10 parameters which you want to pass to the .tpl.php, the theme() call will be quite complicated.

The better approach is to add a preprocess function for the .tpl.php. Modify the custom module in Drupal – Introduction to Drupal Theming @ 2 and add the preprocess function to the .module file.

ykyuen.info

; $Id$
name = Theme customized block
description = Theme the customized block. Ref: https://ykyuen.wordpress.com
package = "YKYUEN"
core = 6.x
version = 6.x-1.0

 

ykyuen.module

<?php

/**
 * Implementation of hook_block().
 */
function ykyuen_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      $blocks[0]['info'] = t('Eureka');
      $blocks[0]['cache'] = BLOCK_NO_CACHE;
      return $blocks;
    case 'view':
      switch ($delta) {
        case 0: 
          $block['content'] = theme('eureka', 'Welcome to Eureka!', 'https://ykyuen.wordpress.com');
          break;
      }
      return $block;
  }
}

/**
 * Implementation of hook_theme().
 */
function ykyuen_theme() {
  return array(
    'eureka' => array(
      'arguments' => array(
        'name' => NULL,
        'link' => NULL
      ),
      'template' => 'eureka',
    )
  );
}

/**
 * Preprocess function for eureka.tpl.php.
 */
function ykyuen_preprocess_eureka(&$variables) {
  $variables['extra'] = "Hello World!";
}

 

Then modify the eureka.tpl.php as follow.

<h2>Theme .tpl.php example</h2>
<p><a href="<?php print $link; ?>"><?php print $name; ?></a></p>
<p><?php print $extra; ?></p>

 

See what you get now.

 

Done =)

Reference:

Advertisement

7 thoughts on “Drupal – Introduction to Drupal Theming @ 3”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.