theme_table

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

includes/theme.inc, строка 1296

Версии
5 – 6
theme_table($header, $rows, $attributes = array(), $caption = NULL)

Возвращает темизированную таблицу.

Каждая ячейка может задаваться либо строкой (содержимым ячейки), либо ассоциативным массивом со следующими ключами:

  • 'data': Строка, которую нужно отобразить в ячейке таблицы.
  • 'header': Является ли эта ячейка заголовком таблицы.
  • Произвольные атрибуты HTML, например, 'colspan'; они будут применены к данной ячейке.

Пример заполнения $rows:

$rows = array(
  // Простая строка
  array(
    'Cell 1', 'Cell 2', 'Cell 3'
  ),
  // Строка с атрибутами; некоторые из ячеек этой строки также содержат атрибуты.
  array(
    'data' => array('Cell 1', array('data' => 'Cell 2', 'colspan' => 2)), 'class' => 'funky'
  )
);

Параметры

$header Массив, содержащий заголовок таблицы. Каждый элемент массива может быть как локализированной строкой, так и ассоциативным массивом с ключами:

  • 'data': Локализированный заголовок колонки.
  • 'field': Колонка таблицы в базе данных (обязательно, если для колонки включена сортировка).
  • 'sort': Порядок сортировки по-умолчанию — по возрастанию ('asc') или по убыванию ('desc').
  • Любые атрибуты HTML, такие как 'colspan'; они будут применены к «заголовочной» ячейке таблицы.

$rows Массив строк таблицы. Каждая строка может являеться массивом ячеек, или ассоциативным массивом с ключами:

  • 'data': массив ячеек
  • Любые атрибуты HTML, такие как 'colspan'; они будут применены к данной строке.

$attributes Любые аттрибуты HTML, для применения к тегу <table>.

$caption Локализированная строка для использоватия в теге <caption>.

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

Представление таблицы в виде HTML.

Связанные темы

▾ 50 функции вызывают theme_table()

aggregator_view in modules/aggregator/aggregator.admin.inc
Отображает страницу администрирования агрегатора.
book_admin_overview in modules/book/book.admin.inc
Возвращает административный краткий обзор всех книг.
contact_admin_categories in modules/contact/contact.admin.inc
Categories/list tab.
dblog_event in modules/dblog/dblog.admin.inc
Коллбэк меню; отображает подробности записи журнала системы.
dblog_overview in modules/dblog/dblog.admin.inc
Коллбэк меню; выводит логи сообщений.
dblog_top in modules/dblog/dblog.admin.inc
Menu callback; generic function to display a page of the most frequent dblog events of a specified type.
filter_filter_tips in modules/filter/filter.module
Реализация hook_filter_tips().
locale_translate_overview_screen in includes/locale.inc
Overview screen for translations.
node_overview_types in modules/node/content_types.inc
Displays the content type admin overview page.
node_revision_overview in modules/node/node.pages.inc
Generate an overview table of older revisions of a node.
openid_user_identities in modules/openid/openid.pages.inc
Menu callback; Manage OpenID identities for the specified user.
path_admin_overview in modules/path/path.admin.inc
Return a listing of all defined URL aliases. When filter key passed, perform a standard search on the given key, and return the list of matching URL aliases.
poll_votes in modules/poll/poll.pages.inc
Callback for the 'votes' tab for polls you can see other votes on
statistics_access_log in modules/statistics/statistics.admin.inc
Menu callback; Displays recent page accesses.
statistics_node_tracker in modules/statistics/statistics.pages.inc
statistics_recent_hits in modules/statistics/statistics.admin.inc
Menu callback; presents the 'recent hits' page.
statistics_top_pages in modules/statistics/statistics.admin.inc
Menu callback; presents the 'top pages' page.
statistics_top_referrers in modules/statistics/statistics.admin.inc
Menu callback; presents the 'referrer' page.
statistics_top_visitors in modules/statistics/statistics.admin.inc
Menu callback; presents the 'top visitors' page.
statistics_user_tracker in modules/statistics/statistics.pages.inc
system_actions_manage in modules/system/system.module
Menu callback. Display an overview of available and configured actions.
theme_aggregator_categorize_items in modules/aggregator/aggregator.pages.inc
Theme the page list form for assigning categories.
theme_book_admin_table in modules/book/book.admin.inc
Theme function for the book administration page form. See alsobook_admin_table()
theme_comment_admin_overview in modules/comment/comment.admin.inc
Темизирует форму комментирования администратора.
theme_filter_admin_order in modules/filter/filter.admin.inc
Темизирует форму конфигурации порядка фильтров.
theme_filter_admin_overview in modules/filter/filter.admin.inc
Theme the admin overview form.
theme_locale_languages_overview_form in includes/locale.inc
Темизирует форму обзора языков сайта.
theme_menu_overview_form in modules/menu/menu.admin.inc
Theme the menu overview form into a table.
theme_node_admin_nodes in modules/node/node.admin.inc
Theme node administration overview.
theme_node_search_admin in modules/node/node.module
Theme the content ranking part of the search settings admin page.
theme_poll_choices in modules/poll/poll.module
Theme the admin poll form for choices.
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_system_modules in modules/system/system.admin.inc
Темизирует форму модулей.
theme_system_modules_uninstall in modules/system/system.admin.inc
Темизирует таблицу отключенных на данный момент модулей.
theme_system_themes_form in modules/system/system.admin.inc
Theme function for the system themes form.
theme_system_theme_select_form in modules/system/system.admin.inc
Темизирует форму выбора темы.
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Темизирует обзор терминов как сортируемый список.
theme_taxonomy_overview_vocabularies in modules/taxonomy/taxonomy.admin.inc
Темизирует обзор словарей как сортируемый список.
theme_trigger_display in modules/trigger/trigger.admin.inc
Display actions assigned to this hook-op combination in a table.
theme_update_report in modules/update/update.report.inc
Темизирует сообщение о состоянии модуля или темы.
theme_upload_attachments in modules/upload/upload.module
Отображение прикрепленных файлов в виде таблицы.
theme_upload_form_current in modules/upload/upload.module
Темизирует список прикрепленных файлов (вложений).
theme_user_admin_account in modules/user/user.admin.inc
Theme user administration overview.
theme_user_admin_new_role in modules/user/user.admin.inc
Theme the new-role form.
theme_user_admin_perm in modules/user/user.admin.inc
Темизирует страницу управления разрешениями.
tracker_page in modules/tracker/tracker.pages.inc
Menu callback. Prints a listing of active nodes on the site.
translation_node_overview in modules/translation/translation.pages.inc
Overview page for a node's translations.
user_admin_access in modules/user/user.admin.inc
Menu callback: list all access rules
_locale_translate_seek in includes/locale.inc
Perform a string search and display results in a table
_system_sql in modules/system/system.admin.inc
Theme a SQL result table.

Код

<?php
function theme_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 = '<table'. drupal_attributes($attributes) .">\n";

  if (isset($caption)) {
    $output .= '<caption>'. $caption ."</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) ? ' <thead><tr>' : ' <tr>');
    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) ? " </tr></thead>\n" : "</tr>\n");
  }
  else {
    $ts = array();
  }

  // Format the table rows:
  if (count($rows)) {
    $output .= "<tbody>\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;
        }

        // Build row
        $output .= ' <tr'. drupal_attributes($attributes) .'>';
        $i = 0;
        foreach ($cells as $cell) {
          $cell = tablesort_cell($cell, $header, $ts, $i++);
          $output .= _theme_table_cell($cell);
        }
        $output .= " </tr>\n";
      }
    }
    $output .= "</tbody>\n";
  }

  $output .= "</table>\n";
  return $output;
}
?>
Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

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