drupal_add_css

Хочешь помочь с переводом? Это очень просто и быстро. Лишь зарегистрируйся, и можешь тут же начать переводить.

includes/common.inc, строка 1752

Версии
5 – 6
drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE)

Добавляет css-файл к списку подгружаемых сss-файлов.

Все CSS файлы, добавляемые модулями, должны иметь префикс с именем данного модуля, например: system-menus.css, а не просто menus.css. В темах оформления эти CSS файлы можно переопределять, используя имена файлов. Префиксы в именах файлов помогут разработчикам тем избежать конфликта имен. Переопределение таблиц стилей происходит в функции drupal_get_css.

If the direction of the current language is right-to-left (Hebrew, Arabic, etc.), the function will also look for an RTL CSS file and append it to the list. The name of this file should have an '-rtl.css' suffix. For example a CSS file called 'name.css' will have a 'name-rtl.css' file added to the list, if exists in the same directory. This CSS file should contain overrides for properties which should be reversed or otherwise different in a right-to-left display.

What does this actually mean? CSS preprocessing is the process of aggregating a bunch of separate CSS files into one file that is then compressed by removing all extraneous white space.

The reason for merging the CSS files is outlined quite thoroughly here: http://www.die.net/musings/page_load_time/

'Load fewer external objects. Due to request overhead, one bigger file
just loads faster than two smaller ones half its size.'

However, you should *not* preprocess every file as this can lead to redundant caches. You should set $preprocess = FALSE when:

  • Your styles are only used rarely on the site. This could be a special admin page, the homepage, or a handful of pages that does not represent the majority of the pages on your site.
Typical candidates for caching are for example styles for nodes across the site, or used in the theme.

Параметры

$path (optional) The path to the CSS file relative to the base_path(), e.g., /modules/devel/devel.css.

$type (optional) The type of stylesheet that is being added. Types are: module or theme.

$media (optional) The media type for the stylesheet, e.g., all, print, screen.

$preprocess (optional) Should this CSS file be aggregated and compressed if this feature has been turned on under the performance section?

Возвращаемое значение

An array of CSS files.

▾ 28 функции вызывают drupal_add_css()

aggregator_init in modules/aggregator/aggregator.module
Реализация hook_init().
block_admin_display_form in modules/block/block.admin.inc
Generate main blocks administration form.
book_init in modules/book/book.module
Реализация hook_init(). Добавляет CSS модуля book.
color_scheme_form in modules/color/color.module
Конструктор формы. Возвращает форму конфигурирования.
comment_render in modules/comment/comment.module
Отображает комментарии.
dblog_init in modules/dblog/dblog.module
drupal_get_css in includes/common.inc
Returns a themed representation of all stylesheets that should be attached to the page.
forum_init in modules/forum/forum.module
Реализация hook_init().
help_main in modules/help/help.admin.inc
Menu callback; prints a page listing a glossary of Drupal terminology.
hook_init in developer/hooks/core.php
Выполняет задачи по инициализации. См. также hook_boot(), hook_exit()
node_init in modules/node/node.module
Реализация hook_init().
openid_form_alter in modules/openid/openid.module
Implementation of hook_form_alter : adds OpenID login to the login forms.
openid_user_identities in modules/openid/openid.pages.inc
Menu callback; Manage OpenID identities for the specified user.
poll_init in modules/poll/poll.module
Реализация hook_init().
search_form in modules/search/search.module
Выводит форму поиска.
system_init in modules/system/system.module
Реализация hook_init().
template_preprocess_maintenance_page in includes/theme.maintenance.inc
The variables generated here is a mirror of template_preprocess_page(). This preprocessor will run it's course when theme_maintenance_page() is invoked. It is also used in theme_install_page() and theme_update_page() to keep all the variables...
template_preprocess_page in includes/theme.inc
Обрабатывает переменные для page.tpl.php
theme_color_scheme_form in modules/color/color.module
Темизирует форму выбора расцветки темы оформления.
theme_profile_admin_overview in modules/profile/profile.admin.inc
Theme the profile field overview into a drag and drop enabled table. See alsoprofile_admin_overview()
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Темизирует обзор терминов как сортируемый список.
theme_taxonomy_term_page in modules/taxonomy/taxonomy.pages.inc
Рендерит HTML-представление страницы термина таксономии.
theme_update_report in modules/update/update.report.inc
Темизирует сообщение о состоянии модуля или темы.
tracker_page in modules/tracker/tracker.pages.inc
Menu callback. Prints a listing of active nodes on the site.
user_init in modules/user/user.module
_drupal_maintenance_theme in includes/theme.maintenance.inc
Sets up the theming system for site installs, updates and when the site is in off-line mode. It also applies when the database is unavailable.
_init_theme in includes/theme.inc
Initialize the theme system given already loaded information. This function is useful to initialize a theme when no database is present.
_locale_translate_language_list in includes/locale.inc
Выводит языки в таблице результатов поиска.

Код

<?php
function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
  static $css = array();
  global $language;

  // Create an array of CSS files for each media type first, since each type needs to be served
  // to the browser differently.
  if (isset($path)) {
    // This check is necessary to ensure proper cascading of styles and is faster than an asort().
    if (!isset($css[$media])) {
      $css[$media] = array('module' => array(), 'theme' => array());
    }
    $css[$media][$type][$path] = $preprocess;

    // If the current language is RTL, add the CSS file with RTL overrides.
    if ($language->direction == LANGUAGE_RTL) {
      $rtl_path = str_replace('.css', '-rtl.css', $path);
      if (file_exists($rtl_path)) {
        $css[$media][$type][$rtl_path] = $preprocess;
      }
    }
  }

  return $css;
}
?>

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

Пример добавления файла CSS в собственном модуле

Реализация хука hook_init:

function имя_модуля_init() {
  drupal_add_css(drupal_get_path('module', 'имя_модуля') .'/имя_модуля.css');
}

Файл стилей должен лежать в корне папки модуля.

Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему