Матросы на зебрахъ, или Как раскрасить Drupal в цвета российского флага

Dec 30, 2008 12:42


Из блога http://shaman.asiadata.ru.

Возникла тут с дикого утреннего бодуна после отгремевшего вчера предновогоднего корпоративчика мысль раскрасить друпал в цвета российского флага. Точнее его таблицы.

Возможность отличить четную строку таблицы от нечетной предоставляется в ядре Drupal, в стандартом выводе таблиц для каждой строки tr присутствуют классы odd и even. А при выводе нод есть переменная с метким названием $zebra, указывающая на четность или нечетность ноды в списке. Но иногда возникает необходимость (дизайнер, гад, нарисовал) отличать каждую третью или десятую строку таблицы и соответствующим образом изменять её внешний вид при помощи CSS-правил.

За вывод табличного содержимого в Drupal отвечает функция theme_table(). Чтобы добавить в вывод таблиц свои возможности надо написать в файле вашей темы template.php пользовательскую функцию с названием phptemplate_table(). Праметры функции должны совпадать с исходной, а код мы скопируем оттуда же и лишь немного дополним его. Для данного примера мои приправы в этот PHP-супчик находятся в строках 65-75:


  1. function phptemplate_table($header, $rows, $attributes = array(), $caption = NULL) {

  2.  

  3.   // Add sticky headers, if applicable.

  4.   if (count($header)) {

  5.     drupal_add_js('misc/tableheader.js');

  6.     // Add 'sticky-enabled' class to the table to identify it for JS.

  7.     // This is needed to target tables constructed by this function.

  8.     $attributes['class'] = empty($attributes['class']) ? 'sticky-enabled' : ($attributes['class'] .' sticky-enabled');

  9.   }

  10.  

  11.   $output = '. drupal_attributes($attributes) .">\n";

  12.  

  13.   if (isset($caption)) {

  14.     $output .= ''. $caption ."\n";

  15.   }

  16.  

  17.   // Format the table header:

  18.   if (count($header)) {

  19.     $ts = tablesort_init($header);

  20.     // HTML requires that the thead tag has tr tags in it follwed by tbody

  21.     // tags. Using ternary operator to check and see if we have any rows.

  22.     $output .= (count($rows) ? ' ' : ' ');

  23.     foreach ($header as $cell) {

  24.       $cell = tablesort_header($cell, $header, $ts);

  25.       $output .= _theme_table_cell($cell, TRUE);

  26.     }

  27.     // Using ternary operator to close the tags based on whether or not there are rows

  28.     $output .= (count($rows) ? " \n" : "\n");

  29.   }

  30.   else {

  31.     $ts = array();

  32.   }

  33.  

  34.   // Format the table rows:

  35.   if (count($rows)) {

  36.     $output .= "\n";

  37.     $flip = array('even' => 'odd', 'odd' => 'even');

  38.     $class = 'even';

  39.     foreach ($rows as $number => $row) {

  40.       $attributes = array();

  41.  

  42.       // Check if we're dealing with a simple or complex row

  43.       if (isset($row['data'])) {

  44.         foreach ($row as $key => $value) {

  45.           if ($key == 'data') {

  46.             $cells = $value;

  47.           }

  48.           else {

  49.             $attributes[$key] = $value;

  50.           }

  51.         }

  52.       }

  53.       else {

  54.         $cells = $row;

  55.       }

  56.       if (count($cells)) {

  57.         // Add odd/even class

  58.         $class = $flip[$class];

  59.         if (isset($attributes['class'])) {

  60.           $attributes['class'] .= ' '. $class;

  61.         }

  62.         else {

  63.           $attributes['class'] = $class;

  64.         }

  65.         switch ($number % 3) {

  66.           case 0:

  67.            $attributes['class'] = empty($attributes['class']) ? 'one' : ($attributes['class'] .' one');

  68.           break;

  69.           case 1:

  70.             $attributes['class'] = empty($attributes['class']) ? 'two' : ($attributes['class'] .' two');

  71.           break;

  72.           case 2:

  73.             $attributes['class'] = empty($attributes['class']) ? 'three' : ($attributes['class'] .' three');

  74.           break;

  75.         }

  76.         // Build row

  77.         $output .= ' . drupal_attributes($attributes) .'>';

  78.         $i = 0;

  79.         foreach ($cells as $cell) {

  80.           $cell = tablesort_cell($cell, $header, $ts, $i++);

  81.           $output .= _theme_table_cell($cell);

  82.         }

  83.         $output .= " \n";

  84.       }

  85.     }

  86.     $output .= "\n";

  87.   }

  88.  

  89.   $output .= "\n";

  90.   return $output;

  91. }

Если кому-то непонятно, почему 0 - это один, 1 - это два, а 2 - это три, отвечу, что так считают даже трезвые программисты.

Теперь добавим в файл стилей темы (обычно style.css) немного краски

.one, tr.one {
  background: white;
}
.two, tr.two {
  background: blue;
}
.three, tr.three {
  background: red;
}

И результат:


Мдя, такие дурацкие ура-патриотические идеи приходят в голову именно с похмелья. Тут, пожалуй, хороший дизайнер должен подобрать цвета получше. Но нам важен принцип работы кода, а не его внешний вид, который может быть любым.

Если вам необходимо использовать в дизайне таблиц пять цветов, то добавленный код дожен быть таким:

switch ($number % 5) {
  case 0:
    $attributes['class'] = empty($attributes['class']) ? 'one' : ($attributes['class'] .' one');
  break;
  case 1:
    $attributes['class'] = empty($attributes['class']) ? 'two' : ($attributes['class'] .' two');
  break;
  case 2:
    $attributes['class'] = empty($attributes['class']) ? 'three' : ($attributes['class'] .' three');
  break;
  case 3:
    $attributes['class'] = empty($attributes['class']) ? 'four' : ($attributes['class'] .' four');
  break;
  case 4:
    $attributes['class'] = empty($attributes['class']) ? 'five' : ($attributes['class'] .' five');
  break;
}

А если просто выделить каждую десятую строку, то так:

if($number % 10 == 9) $attributes['class'] = empty($attributes['class']) ? 'ten' : ($attributes['class'] .' ten');
И не забудьте про соответствующие этим классам CSS-правила в файле стилей.

ЗЫ. Всех с Новым 2009-м годом!

Заметки начинающего друпаллурга, drupal 6, phptemplate engine

Previous post Next post
Up