Drupal

Adding zebra classes to Drupal 6 search results

August 3, 2011

Drupal 6 search results lack the odd class we’ve come to expect when creating a style for every other row in a list. Drupal 6 search results give us a plain definition list inside of a row. Using the template.php file and the search-results.tpl.php files in our theme, we can add an even:odd class to each wrapping row.

Starting with our template.php file, we want to use the function: template_preprocess_search_results(&$variables) to add logic and a new variable. The default code for this function looks like this:

<?php

    function template_preprocess_search_results(&$variables) {

        $variables['search_results'] = '';

        foreach ($variables['results'] as $result) {
            $variables['search_results'] .= theme('search_result', $result, $variables['type']);
        }

        $variables['pager'] = theme('pager', NULL, 10, 0);

        // Provide alternate search results template.
        $variables['template_files']\[] = 'search-results-' . $variables['type'];

    }

By adding a simple foreach loop, we can create a new ‘zebra’ variable for our search results template.

    foreach ($variables['results'] as $key => $value) {

        $variables['results']\[$key]\['zebra'] = ($key % 2) ? 'odd' : 'even';

    }

The final function would look like this:

<?php

    /*
    \* Implementation of preprocess_search_results
    \*/

    function magenta_preprocess_search_results(&$variables) {
        foreach ($variables['results'] as $key => $value) {
            $variables['results']\[$key]\['zebra'] = ($key % 2) ? 'odd' : 'even';
        }

        $variables['search_results'] = '';

        foreach ($variables['results'] as $result) {
            $variables['search_results'] .= theme('search_result', $result, $variables['type']);
        }

        $variables['pager'] = theme('pager', NULL, 10, 0);

        // Provide alternate search results template.
        $variables['template_files']\[] = 'search-results-' . $variables['type'];

    }

Now we just need to print the variable in our search-results.tpl.php file. The modified code looks like this:

<div class="row <?php print $variables['zebra'];?>">
    <dt class="title">
        <a href="<?php print $url; ?>"><?php print $title; ?></a>
    </dt>
    <dd>
        <?php if ($snippet) : ?>
            <p class="search-snippet"><?php print $snippet; ?></p>
        <?php endif; ?>
        <?php if ($info) : ?>
            <p class="search-info"><?php print $info; ?></p>
        <?php endif; ?>
    </dd>
</div>

Now we can add our css to target the even:odd classes on each row.

For more information about overriding templates or using the template.php file, check out the documentation on drupal.org.

#Drupal 6