Из блога
http://shaman.asiadata.ru.
Возникла тут с дикого утреннего бодуна после отгремевшего вчера предновогоднего корпоративчика мысль раскрасить друпал в цвета российского флага. Точнее его таблицы.
Возможность отличить четную строку таблицы от нечетной предоставляется в ядре Drupal, в стандартом выводе таблиц для каждой строки tr присутствуют классы odd и even. А при выводе нод есть переменная с метким названием $zebra, указывающая на четность или нечетность ноды в списке. Но иногда возникает необходимость (дизайнер, гад, нарисовал) отличать каждую третью или десятую строку таблицы и соответствующим образом изменять её внешний вид при помощи CSS-правил.
За вывод табличного содержимого в Drupal отвечает функция
theme_table(). Чтобы добавить в вывод таблиц свои возможности надо написать в файле вашей темы template.php пользовательскую функцию с названием phptemplate_table(). Праметры функции должны совпадать с исходной, а код мы скопируем оттуда же и лишь немного дополним его. Для данного примера мои приправы в этот PHP-супчик находятся в строках 65-75:
function phptemplate_table($header, $rows, $attributes = array(), $caption = NULL) {
// Add sticky headers, if applicable.
if (count($header)) {
drupal_add_js('misc/tableheader.js');
// Add 'sticky-enabled' class to the table to identify it for JS.
// This is needed to target tables constructed by this function.
$attributes['class'] = empty($attributes['class']) ? 'sticky-enabled' : ($attributes['class'] .' sticky-enabled');
}
$output = '. drupal_attributes($attributes) .">\n";
if (isset($caption)) {
$output .= ''. $caption ."\n";
}
// Format the table header:
if (count($header)) {
$ts = tablesort_init($header);
// HTML requires that the thead tag has tr tags in it follwed by tbody
// tags. Using ternary operator to check and see if we have any rows.
$output .= (count($rows) ? ' ' : ' ');
foreach ($header as $cell) {
$cell = tablesort_header($cell, $header, $ts);
$output .= _theme_table_cell($cell, TRUE);
}
// Using ternary operator to close the tags based on whether or not there are rows
$output .= (count($rows) ? " \n" : "\n");
}
else {
$ts = array();
}
// Format the table rows:
if (count($rows)) {
$output .= "\n";
$flip = array('even' => 'odd', 'odd' => 'even');
$class = 'even';
foreach ($rows as $number => $row) {
$attributes = array();
// Check if we're dealing with a simple or complex row
if (isset($row['data'])) {
foreach ($row as $key => $value) {
if ($key == 'data') {
$cells = $value;
}
else {
$attributes[$key] = $value;
}
}
}
else {
$cells = $row;
}
if (count($cells)) {
// Add odd/even class
$class = $flip[$class];
if (isset($attributes['class'])) {
$attributes['class'] .= ' '. $class;
}
else {
$attributes['class'] = $class;
}
switch ($number % 3) {
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;
}
// Build row
$output .= ' . drupal_attributes($attributes) .'>';
$i = 0;
foreach ($cells as $cell) {
$cell = tablesort_cell($cell, $header, $ts, $i++);
$output .= _theme_table_cell($cell);
}
$output .= " \n";
}
}
$output .= "\n";
}
$output .= "\n";
return $output;
}
Если кому-то непонятно, почему 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-м годом!