使用template.php将CSS类动态添加到视图行


8

我实际上已经到达了Google的底部,试图弄清楚如何向视图的每一行添加一个CSS类。诀窍在于,我需要根据视图所来自的节点中的某些数据来动态确定每一行的类。为节点巧妙地实现这一目标的功能是-

function pgc_preprocess(&$variables) {
  $node = $variables['node'];
  if ($node->type == "event") {
    $variables['event_class'] = '';
    $num_trainers = $node->field_number_of_trainers[0]['value'];
    $count = count($node->field_trainer);
    if($count < $num_trainers) {
        $variables['event_class'] = 'red';
    } else {
        $variables['event_class'] = 'green';
    }
    return $variables;
  }
}

这样做的目的是对没有足够人注册的事件进行颜色编码。首页上将有一个事件列表,我还需要对它们进行颜色编码。我真的希望有一些简单的解决方案-

function pgc_preprocess_views_view_unformatted(&$variables) {
  // Magic here, preferably having something to 
  // do with the function I already wrote.
}

只是放入<?php print $event_class ?>视图.tpl并不会这样做。


可能不认为这是一种好习惯(将php逻辑放入tpl中),但是将其直接放在tpl行中怎么办?
tostinni

1
那不是CSS类,那是HTML。它应该是语义的。尝试使用有意义的类,并为CSS保留红色/绿色。
Capi Etheriel

Answers:


10
function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    $vars['classes'][$id] .= ' ' . $event_class;
  }
}

function get_the_classes($nid) {
  $node = node_load($nid);
  global $user;
  if ($user->uid != 0) { // Not for anon users.
    $event_class = '';
    if ($node->field_trainer[0]['uid'] == NULL) {
        $event_class= 'red';
    } else {
        $num_trainers = $node->field_number_of_trainers[0]['value'];
        $count = count($node->field_trainer);
        if($count < $num_trainers) {
            $event_class = 'red';
        } else {
            $event_class = 'green';
        }
    }
    return $event_class;
  }
}

不知道它是否漂亮。不知道它的表现。但这有效。

编辑(02-01-2012):在与Drupal一起工作了一年之后,除了node_load()在视图的每一行上运行之外,我还试图找到其他方法来做到这一点。


5
注意:在template_preprocess_views_view方法中,您可以通过$ view-> result [$ id]-> _ field_data ['nid'] ['entity']访问节点/实体数据(因此避免在每一行上使用node_load())
g10

0

您的解决方案很棒!为了确保将类确实添加到视图行类中,您应该添加

$vars['classes_array'][$id] = implode(' ', $vars['classes'][$id]);

$vars['classes'][$id][] = $event_class;

预处理功能将是:

function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    if($event_class != '') {
        $vars['classes'][$id][] = $event_class;
        $vars['classes_array'][$id] = implode(' ', $vars['classes'][$id]);
    }
  }

}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.