Drupal: Советы и трюки (Часть I)

Drupal-Logo.png
Всегда интересно прикручивать к Drupal интересные «плюшки» без использования модулей. Рассмотрим несколько из них, использовать их в своих проектах или нет — ваше право. Так же, рассмотрено несколько вопросов по темизации.

Проверка заполнения полей с jQuery

Мне лично не нравится валидатор Drupal'а и я интегрировал jquery.validate

Собственно интегрировать его не проблема.
Скачайте плагин.
Создайте директорию js в директории вашей темы и поместите туда jquery.validate.min.js.

Откройте ВАША_ТЕМА.info и подключите там плагин:

scripts[] = js/jquery.validate.min.js

Директория js должна находится по пути /sites/all/themes/ваша_тема/

Создайте файл scripts.js в директории /sites/all/themes/ваша_тема/js/ и пропишите в нём следующее:

$().ready(function() {
        $("#comment-form").validate();
      });

Где #comment-form — идентификатор формы

Примечание: в этот же файл вы можете вставлять все свои скрипты. Не забудьте прописать scripts.js в info-файле темы!


Решение target=_blank

Вставляем этот код в /sites/all/themes/ваша_тема/js/scripts.js

$(function(){
        $('._blank a').click(function(){
          window.open(this.href);
          return false;
        });
      });

Пример использования:

<span class="_blank><a href="http://habrahabr.ru">Habrahabr</a></span>

Или, если ссылка встречается в тексте —

<div class="content _blank">
    <p>
    <a href="http://www.lipsum.com/">Lorem ipsum</a> dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. <a href="http://www.lipsum.com/">Excepteur</a> sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    </div>

Решение target=_blank (2 вариант)

$('a[rel$="external"]').click(function(){
 this.target = "_blank";
});

Пример использования:

<a href="http://habrahabr.ru/" rel="external">Habrahabr</a>


Добавление тега span в primary/secondary_links

Вставляем этот код в /sites/all/themes/ваша_тема/js/scripts.js

// Wrap span tags around the anchor text in the primary menu.
    $(document).ready(function(){
     $("#primary li a")
     .wrapInner("<span>" + "</span>");
    });

и в template.php нашей темы этот код:

/**
    * Override the theme_links function
    *
    * We use this to insert <span></span> tags around anchor text in the
    * primary and secondary links. We need these to support Internet Explorer
    * when building sliding door tabs with hover effects.
    */
    function ВАША_ТЕМА_links($links, $attributes = array('class' => 'links')) {
     $output = '';
     if (count($links) > 0) {
      $output = '<ul'. drupal_attributes($attributes) .'>';
 
      $num_links = count($links);
      $i = 1;
 
      foreach ($links as $key => $link) {
       $class = $key;
 
       // Add first, last and active classes to the list of links to help out themers.
       if ($i == 1) {
        $class .= ' first';
       }
       if ($i == $num_links) {
        $class .= ' last';
       }
       if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))) {
        $class .= ' active';
       }
 
       $output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
 
       // wrap <span>'s around the anchor text
       if (isset($link['href'])) {
        $link['title'] = '<span>' . check_plain($link['title']) . '</span>';
        $link['html'] = TRUE;  
        // Pass in $link as $options, they share the same keys.
        $output .= l($link['title'], $link['href'], $link);   
       }
       else if (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in <span> for adding title and class attributes
        if (empty($link['html'])) {
         $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
         $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
       }
 
       $i++;
       $output .= "</li>\n";
      }
 
      $output .= '</ul>';
     }
     return $output;
    }


Изменяем «добавлено...»

код нужно поместить в template.php вашей темы

//In node
function ВАША_ТЕМА_node_submitted($node) {
 return t('Posted by !username on @date', array(
    '!username' => theme('username', $node),
    '@date' => format_date($node->created, 'custom', 'd / M / Y- H:i')
 ));
}
//In comment
function ВАША_ТЕМА_comment_submitted($comment) {
 return t('Posted by !username on @date at about @time.', array(
  '!username' => theme('username', $comment),
  '@date' => format_date($comment->timestamp, 'custom', 'd / M / Y- H:i'),
  '@time' => format_date($comment->timestamp, 'custom', 'H:i')
 ));
}

Показываем количество комментариев

Если они есть, покажется их количество, если нет, то не покажется ничего, например, так сделано на Drupalogy.ru

/**
* Preprocessor for theme('comment_wrapper').
*/
function ВАША_ТЕМА_preprocess_comment_wrapper(&$vars) {
 $vars['hook'] = 'box';
 $vars['attr']['id'] = 'comments';
 $vars['attr']['class'] .= ' clear-block';
 
 if ($vars['content'] && $vars['node']->type != 'forum' && $vars['node']->comment_count != 0) {
  $vars['content'] = '<h2 class="box-title">'. t('Comments') .'</h2>'. $vars['content'];
 }
}

Советую обратить внимание:
Как прикрутить типограф к BUeditor

Share/Bookmark В закладки

Комментарии

Аноним аватар
Аноним
28/03/2011 - 15:00

спасибо за полезный код!