Добавление класса на основе опубликованного состояния


Я пытаюсь добавить класс тела на свой сайт в template.php в зависимости от того, опубликован узел или нет. Я осмотрелся здесь и дальше drupal.org и собрал воедино какой-то код, но я получаю ошибку. Вот что я пробовал до сих пор:

function responsive_process_html(&$variables) { 

 if ($node->status == 1){
        //$variables['#attributes']['class'][] = 'pub';
        $variables['classes_array'][] = 'published';
    }

    else {
        $variables['classes_array'][] = 'not-published';
    }
}

... но я получаю эту ошибку:

Notice: Undefined variable: node in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).
Notice: Trying to get property of non-object in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).

Я также попробовал $variables['#attributes']['class'][] = 'published'; вместо $variables['classes_array'][] = 'published';, но это не имело никакого значения.

 1
Author: Danny Englander, 2012-08-14

3 answers

В вашей теме template.php :

function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}
 4
Author: Andre Baumeier, 2014-03-02 13:35:06

В итоге я нашел милую маленькую функцию из темы Дзен (7.x-5.1). В template.php добавьте эту функцию узла предварительной обработки:

function MY_THEME_preprocess_node(&$variables, $hook) {
        // Add $unpublished variable.
        $variables\['unpublished'\] = (!$variables\['status'\]) ? TRUE : FALSE;
    }

Затем в node.tpl.php или ваш node--custom.tpl.php возьмите переменную unpublished и добавьте что-то вроде этого:

 <?php if ($unpublished): ?>
    <!-- whatever code you want here using the variable-->
    <p class="unpublished"><?php print t('Unpublished'); ?></p>
 <?php endif; ?>

Затем вы можете оформить это так, как захотите, и это отличный визуальный индикатор для пользователя, что узел не опубликован. (см. Снимок экрана).

enter image description here

 2
Author: Danny Englander, 2012-08-15 16:18:35

Эта переменная $node не определена, но может быть передана внутри...

$node=$variables['node'];

if (!empty($node)) { // we are displaying a node

  if ($node->status) {
    // we are published
  } else {
    // we aren't published
  }

} else { // we are in a view or another none node type page
  // do whatever here then
}

... если вы отображаете полную страницу узла, я бы проверил, есть ли она там. Это было бы в preprocess_page(), поэтому может быть доступно и для preprocess_html().

ДОПОЛНЕНИЕ:

Например, посмотрите, работает ли это....

function YOURTHEME_OR_MODULE_preprocess_html(&$variables) {

  $node=$variables['node'];

  if (!empty($node)) {

    if ($node->status) {
      $variables['classes'].=' published';
    } else {
      $variables['classes'].=' not-published';
    }

  }

}

...но я просто смотрю на код, так как у меня нет тестового стенда D7, на котором можно было бы это запустить.

 1
Author: Jimajamma, 2012-08-15 16:00:02