background image

Content tagged with: template

Eric's picture

I created a Drupal site to host my photography in CCK Imagefield nodes and used Lucene to enhance my search functionality. By default Drupal's search results are text-based so I decided to add some code to show image thumbnails in my search results. I checked out Drupal Lucene's hooks and decided to implement a hook_luceneapi_result_alter() function in my existing module.

<?php
function MYMODULE_luceneapi_result_alter(&$result, $module, $type = NULL) {
 
 
// check for node results
 
if ($type == 'node') {
 
   
// check node type
   
if ($result['node']->type == 'image') {
   
     
// define an imagecache image path for image thumbnail
     
$imagecache_path_thumbnail = file_directory_path() . '/imagecache/thumbnail' . str_replace(file_directory_path(),'',$result['node']->field_image[0]['filepath']);     
     
     
// define an imagecache image path for image (large)
     
$imagecache_path_large = file_directory_path() . '/imagecache/large' . str_replace(file_directory_path(),'',$result['node']->field_image[0]['filepath']);
   
     
// define theme_image() variables
     
$alt = check_plain($result['node']->title);
     
$title = check_plain($result['node']->title);
     
// add rel=lightbox to enable lightbox2 module
     
$attributes = array(
       
'rel' => 'lightbox',
      );
     
// let imagecache define the size
     
$getsize = FALSE;
     
// generate the image hml
     
$image_html = theme('image', $imagecache_path_thumbnail, $alt, $title, $attributes, $getsize);     
   
      if (
$image_html) {
               
       
// define lightbox link
       
$image_link = l(
         
$image_html,
         
$imagecache_path_large,
          array(
           
'html' => true,
           
'attributes' => array(
             
'rel' => 'lightbox',
            )
          )
        );

       
// add data to the result variable, passed by reference
       
$result['image_thumbnail'] = $image_link;
       
      }
   
    }
 
  }

}
?>

The above code adds additional data to my search results variables. I then implemented a hook_preprocess_search_result() function in my theme's template.php file to pass this data to the search-result.tpl.php template file.

<?php
function MYTHEME_preprocess_search_result(&$variables) {

 
// ...snip...

  // check for lucene node search results
 
if ($variables['type']=='luceneapi_node') {

   
// check for image
   
if ($variables['result']['image_thumbnail']) {   

     
// pass additional data to theme template file
     
$variables['image_thumbnail'] = $variables['result']['image_thumbnail'];

    }
   
  }

}
?>

And in my theme's search-result.tpl.php template file, I added the following PHP to show the new variable.

<div class="search-result <?php print $search_zebra; ?>">

  <?php if($image_thumbnail): ?>
    <?php print $image_thumbnail; ?>
  <?php endif; ?>

  <!-- ...snip... -->

I also added a few lines of CSS in my theme's style.css file to tidy up the layout.

.search-results.luceneapi_node-results .search-result {
  clear: both;
}

.search-results.luceneapi_node-results .search-result img {
  float: left;
  margin: 0px 20px 20px 0px;
}

The visual results can be seen here on my photo gallery.

Visual search results

Eric's picture

In this blog entry, I'll show you how you can add some module code to allow users to select different themes for their profile page. I decided to use the standard user-profile.tpl.php as the base template. I copied this file into my theme folder and replicated it a few times. I named the files:

user-profile-version-1.tpl.php
user-profile-version-2.tpl.php

For my example, I simply added the text "Version 1" and "Version 2" to the top of these files to show it's working, but you could revise the layout, add CSS, etc.

Next, I created a module to contain all the following code. I defined a hook_perm() and hook_menu() function to add a menu local task (tab) to the user page.

<?php
function MYMODULE_perm() {
  return array(
   
'choose profile theme'
 
);
}

function
MYMODULE_menu() {
 
 
$items = array();
 
 
$items['user/%user/choose-profile-them'] = array(
   
'title' => 'Choose Profile Theme',
   
'page callback' => '_MYMODULE_callback_choose_profile_theme',
   
'page arguments' => array(1),
   
'access callback' => 'user_access',
   
'access arguments' => array('choose profile theme'),
   
'type' => MENU_LOCAL_TASK,
  );
 
  return
$items;
 
}
?>

user profile tab

Next, I defined the page callback to create a list of available templates for the user to choose from.

<?php
function _MYMODULE_callback_choose_profile_theme($user) {

 
// create an empty strong variable for page html
 
$html = "";

 
// define a list of available profile templates
 
$profileTemplates = array(
   
'user-profile-version-1' => 'Version 1',
   
'user-profile-version-2' => 'Version 2'
 
);
 
 
// loop through templates and ensure they exist
 
foreach ($profileTemplates as $template => $name) {
    if (!
file_exists(path_to_theme() . '/' . $template . '.tpl.php')) {
      unset(
$profileTemplates[$name]); 
    }
  }
 
  if (
count($profileTemplates)) {
   
$html .= drupal_get_form('_MYMODULE_callback_choose_profile_theme_form', $user, $profileTemplates);
  } else {
   
$html .= "No profile themes currently exist.";
  }
 
  return
$html;
 
}
?>

The following functions define the form array, and validation and submit handlers. When the form is submitted, the template option is saved to the user account variables using the user_save() function.

<?php
function _MYMODULE_callback_choose_profile_theme_form($form_state, $user, $profileTemplates) {

 
$form = array();
 
 
// add a select input element
 
$form['profileTemplate'] = array(
   
'#type' => 'select',
   
'#title' => t('Profile Template'),
   
'#options' => $profileTemplates,
   
'#default_value' => $GLOBALS['user']->profileTemplate
 
);
 
 
// add a submit button
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit')
  );
 
 
// add hidden element for userID
 
$form['userID'] = array(
   
'#type' => 'hidden',
   
'#value' => $user->uid
 
);
 
  return
$form;
}

function
_MYMODULE_callback_choose_profile_theme_form_validate($form, &$form_state) {
 
// TODO: add your additional form validation here
 
  // ensure userID submitted matches current user
 
if ($form_state['values']['userID']!=$GLOBALS['user']->uid) {
   
form_set_error('', t('Error processing form.')); 
  }
 
}

function
_MYMODULE_callback_choose_profile_theme_form_submit($form, &$form_state) {

 
// load user object
 
$user = user_load($form_state['values']['userID']);
 
 
// save profile template to user variables
 
user_save($user, array('profileTemplate' => $form_state['values']['profileTemplate']));
 
 
// set a message
 
drupal_set_message('Your profile template has been set.');
 
}
?>

user profile form

Last, I defined the preprocess function to see if a template has been set in the user variables, and add the templates suggestion to change the user profile template.

<?php
function MYMODULE_preprocess_user_profile(&$variables) {

 
// ensure the template file exists, and is set in the user object
 
if (file_exists(path_to_theme() . '/' . $variables['user']->profileTemplate . '.tpl.php') && $variables['user']->profileTemplate) {

   
// set a templates suggestion
   
$variables['template_files'][] = $variables['user']->profileTemplate;
  }
 
}
?>

As you can see below, when I choose the "Version 2" template option, the file "user-profile-version-2.tpl.php" is being loaded, and the text "Version 2" is displayed at the top of the page.

user profile selected

Eric's picture

In this tutorial I'll show you how you can add jQuery image carousel functionality to your CCK node. This tutorial requires you to install the following modules:

cck
filefield
imageapi
imagecache
imagefield

NOTE: The next few steps assume you have not already setup a content type and ImageCache preset. You can ignore them if you already have.

Once you installed the above modules and set permission accordingly, you'll need to define an ImageCache preset (/admin/build/imagecache/add). I called mine "thumbnail" for this example. I added a "Add Scale" action to set the width to 100 (pixels). This will ensure when you create an image, a thumbnail will be created automatically.

Create a new content type (/admin/content/types/add). I called mine "Carousel" for this example. I then clicked on "Manage Fields" (/admin/content/node-type/carousel/fields) to setup a new Image field. I called my new field "field_images", selected "File" for field type, and selected "Image" for the form element.

On the next screen, scroll down to the Global fieldset region and enable the "Required" checkbox, and set the "Number of Values" to "Unlimited". This will allow the user to upload numerous image files to the same CCK field.

Next, you'll want to set which image preset it shown when viewing the node, by clicking on "Display fields" (/admin/content/node-type/carousel/display). I chose the "thumbnail image" preset for both the teaser and full node displays.

I then created a new carousel node (/node/add/carousel). I used the "Add another item" button to upload three images to this node.

If you view the node, the images will be stacked vertically.

This is where the fun starts. You'll need to download the jQuery Carousel library (http://sorgalla.com/projects/jcarousel/). I downloaded the jcarousel.zip file and unpacked it. Copy the entire unpacked jcarousel folder into your theme directory.

Now, you'll need to add a preprocess_node function to your template.php file:

<?php
function YOURTHEME_preprocess_node(&$variables) {
 
 
// test for carousel node type
 
if ($variables['type'] == 'carousel') {

   
// include jCarousel javascript
   
drupal_add_js(path_to_theme() . '/jcarousel/lib/jquery.jcarousel.js');
   
   
// add jquery in enable jQuery carousel on <ul>
   
$js = "
      $(document).ready(function(){
        $('#mycarousel').jcarousel();
      });
    "
;
   
drupal_add_js($js, 'inline');
   
   
// include jCarousel css
   
drupal_add_css(path_to_theme() . '/jcarousel/lib/jquery.jcarousel.css');
   
drupal_add_css(path_to_theme() . '/jcarousel/skins/tango/skin.css');
   
   
// loop through images and create an item list
   
$items = array();
    foreach (
$variables['field_images'] as $key => $value) {
     
$items[] = $value['view'];
    }
   
   
// ensure images exist
   
if (count($items)) {
     
// add jQuery carousel html to $content variable
     
$variables['content'] .= theme('item_list', $items, NULL, 'ul', array('id' => 'mycarousel', 'class' => 'jcarousel-skin-tango'));
    }
   
  }
 
}
?>

The previous code snippet should result in the following:

If you'd like you can hide the old image html by adding a single line of CSS (or by adding more elaborate code in your template preprocess function).

Example:

div.field-field-images {
  display: none;
}

Adding the previous CSS will result in this example:

Eric's picture

In order to promote readable and scalable themes (and modules), it's important to plan the organization of your template files and preprocess functions. If you find yourself putting too much PHP code in a template file, you might need to move that code into a preprocess function. On the other hand, if you find yourself putting too much HTML in a function, you might need to create your own template file.

In this code snippet, I'll show you how you can create and define your own template files to be used in your Drupal site. The first thing to do is find a section of your code that has a significant amount of HTML scattered throughout.

Let's take this sample piece of code for example:

<?php
$html
= "";
$myVar = "HTML";
$html .= "<div>HERE IS A LARGE AMOUNT OF <b>"
 
. $myVar . "</b> BEING CREATED.</div>";
return
$html;
?>

For this example, I'm going to convert the statement that creates the HTML into its own template file. I'll start by creating a new file in my template directory called "example.tpl.php". I'll then copy the following into my new file:

<div>
  HERE IS A LARGE AMOUNT OF <b><?php print $myVar; ?></b> BEING CREATED.
</div>

Notice that I had to enclose my variable in PHP tags with a print statement. This is because the template file will be treated as HTML, just like node.tpl.php or block.tpl.php.

Now, we have to let our theme know that we created a template file by defining a hook_theme(). The hook_theme() function resides in the template.php file of your theme, please read more about it here. In your hook_theme() function, you return an associative array of theme implementations along with their arguments and template names.

<?php
function MYTHEME_theme() {
  return array(
   
'MYTHEME_example' => array(
     
'template' => 'example',
     
'arguments' => array('myVar' => null),
    )
  );
}
?>

At this point, you'll have to flush your theme registry before hook_theme() is processes and your new template file is available. Once that's done, you can use the theme() function to call your theme implementation. Let's replace the original example with a theme() function call:

<?php
$html
= "";
$myVar = "HTML";

/*
$html .= "<div>HERE IS A LARGE AMOUNT OF <b>"
  . $myVar . "</b> BEING CREATED.</div>";
*/
$html .= theme('MYTHEME_example', $myVar);

return
$html;
?>

In the above snippet, I used the theme() function to call my template implementation called "MYTHEME_example" and passed it one argument "myVar". As long as you defined arguments in hook_theme(), they will be passed into your template scope. The following will be contents of the $html variable:

<div>
  HERE IS A LARGE AMOUNT OF <b>HTML</b> BEING CREATED.
</div>

Eric's picture
  • Most importantly, read all the documentation
  • Second most important, learn when to use a preprocess function versus a template file. The Devel module's Theme Information will help determine the name of core template suggestions and preprocess functions
  • Put your code in a preprocess functions, your html in tpl.php files, and your CSS in a style sheet. Avoid mixing these files when possible. Following the rules of MVC frameworks will help promote flexible and clean code
  • Before creating a new template file (or preprocess function), see if the theme can be adjusted using: 1) a configuration change (for example, changing a view's layout); or 2) simply adding or modifying CSS
  • If you find yourself reusing code, create a function in template.php to promote consistency
  • Include javascript and style sheets conditionally to improve performance and reduce overhead
  • Avoid using inline style or javascript. Put CSS in a style sheet; and use drupal_add_js() to include javascript
  • When creating new template files, be sure to register them in hook_theme() and use the theme() function to call them
  • When creating a new tpl.php template file, make sure to include the same variables used in the default template, or you might be missing something in your theme (tabs, title, help, etc).
  • When defining new variables in a preprocess function, prefix the variable names with a common identifier so you call easily tell your custom variables apart from the Drupal default variables.
  • When theming a view, take advantage of the "Theme: Information" link under basic settings to help determine the right template file to use. For instance, if you want to modify the output for a single field, don't create a views-view.tpl.php file; use a views-view-field.tpl.php file instead
  • Keep scalability in mind at all times. For instance, when theming a view, will your code break if the admin switches from a page layout to a block layout? Also, try to avoid setting a fixed height on regions, there is no telling how many content items & blocks the user will attempt to assign to a region.
  • When creating regions and columns in your theme, test for their contents before displaying them. If your regions do not have any blocks assigned, you can increase the size of your main column/region and avoid large areas of awkward white space.
  • When theming a menu block in a region, user CSS selectors specific to the region (not the block). That way when you assign another menu to the same region, you will not have to replicate the CSS for the menu block.
  • Modify forms using hook_form_alter() when possible
  • Use file versioning software like Subversion to track and deploy your theme edits
  • NOTE: more tips coming soon, please check back again.