format_plural

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

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

Версии
5
format_plural($count, $singular, $plural)
6
format_plural($count, $singular, $plural, $args = array(), $langcode = NULL)

Форматирует и переводит строку, содержащую число.

Функция обеспечивает корректное форматирование и перевод строк с числителями. Так как функция вызыват t(), не передавайте в нее уже переведенные значения.

Например:

$output = format_plural($node->comment_count, '1 comment', '@count comments');

Примеры с дополнительными подстановками:

$output = format_plural($update_count,
'Changed the content type of 1 post from %old-type to %new-type.',
'Changed the content type of @count posts from %old-type to %new-type.',
array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));

Параметры

$count Число для подстановки.

$singular Строка в единичном числе. Используйте строки, в которых явно выраженно единичное число, дабы упростить дальнейший перевод (напр. используйте '1 new comment' вместо '1 new'). Кроме того, здесь запрещено использовать '@count'.

$plural Строка для множественного значения. Используйте '@count' в месте, где должна подставиться цифра, например

'@count
new comments'
.

$args Ассоциативный массив подстановок для перевода. При встрече ключей массива в строке перевода, они заменяются на соответствующие значения. В зависимости от первого символа в ключе, значения экранируются или приводятся в надлежайший вид:

  • !variable: вставляется без изменений;
  • @variable: очищается от HTML (check_plain());
  • %variable: очищает текст и темизируется как "заполнитель" для введенных пользователем данных (check_plain() + theme_placeholder());
Вы не должны вставлять '@count' в этот массив. Это делается автоматически.

$langcode Необязательный код языка для перевода на язык отличный от используемого для отображения страницы.

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

Переведенная строка.

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

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

actions_synchronize in includes/actions.inc
Синхронизирует действия, переданные из модуля.
aggregator_view in modules/aggregator/aggregator.admin.inc
Отображает страницу администрирования агрегатора.
comment_link in modules/comment/comment.module
Реализация hook_link().
comment_nodeapi in modules/comment/comment.module
Реализация hook_nodeapi().
format_interval in includes/common.inc
Форматирует временной интервал с заданной точностью.
format_size in includes/common.inc
Генерирует строчное представление указанного количества байт.
hook_link in developer/hooks/core.php
Определяет внутренние ссылки Drupal.
menu_delete_menu_confirm in modules/menu/menu.admin.inc
Build a confirm form for deletion of a custom menu.
menu_edit_menu_validate in modules/menu/menu.admin.inc
Validates the human and machine-readable names when adding or editing a menu.
node_node_type in modules/node/content_types.inc
Implementation of hook_node_type().
node_title_list in modules/node/node.module
Gather a listing of links to nodes.
node_type_delete_confirm in modules/node/content_types.inc
Menu callback; delete a single content type.
poll_page in modules/poll/poll.pages.inc
Menu callback to provide a simple list of all polls available.
search_admin_settings in modules/search/search.admin.inc
Menu callback; displays the search module settings page. See alsosystem_settings_form()
statistics_link in modules/statistics/statistics.module
Реализация hook_link().
system_modules_confirm_form in modules/system/system.admin.inc
Display confirmation form for dependencies.
template_preprocess_forum_list in modules/forum/forum.module
Process variables to format a forum listing.
template_preprocess_forum_topic_list in modules/forum/forum.module
Preprocess variables to format the topic listing.
throttle_exit in modules/throttle/throttle.module
Implementation of hook_exit().
tracker_page in modules/tracker/tracker.pages.inc
Menu callback. Prints a listing of active nodes on the site.
upload_link in modules/upload/upload.module
Реализация hook_link().
upload_nodeapi in modules/upload/upload.module
Implementation of hook_nodeapi().
user_block in modules/user/user.module
Реализация hook_block().
_aggregator_items in modules/aggregator/aggregator.module
Helper function for drupal_map_assoc.
_locale_batch_language_finished in includes/locale.inc
Finished callback of language addition locale import batch. Inform the user of translation files imported.
_locale_batch_system_finished in includes/locale.inc
Finished callback of system page locale import batch. Inform the user of translation files imported.
_locale_import_po in includes/locale.inc
Parses Gettext Portable Object file information and inserts into database
_node_mass_update_batch_finished in modules/node/node.admin.inc
Node Mass Update Batch 'finished' callback.

Код

<?php
function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
  $args['@count'] = $count;
  if ($count == 1) {
    return t($singular, $args, $langcode);
  }

  // Get the plural index through the gettext formula.
  $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
  // Backwards compatibility.
  if ($index < 0) {
    return t($plural, $args, $langcode);
  }
  else {
    switch ($index) {
      case "0":
        return t($singular, $args, $langcode);
      case "1":
        return t($plural, $args, $langcode);
      default:
        unset($args['@count']);
        $args['@count['. $index .']'] = $count;
        return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
    }
  }
}
?>

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

Есть один подводный камень функции. Строку в параметре $singular нужно переводить на русский, заменяя еденицу на @count. Например: '1 comment' — '@count комментарий'.

Если этого не сделать, вы получите неправильный перевод строк с числами, заканчивающимися на еденицу (21, 91, ...).

Пояснение сделано на сервере переводов - Как правильно переводить числительные, но и здесь стоит дополнить предыдущий комментарий.

Для русского языка единственным правильным вариантом перевода является:

1) единственная форма - заменить [1 или One] на (@|%)count
2) вторая форма - использовать (@|%)count
3) третья форма - использовать (@|%)count[2]

Например:

msgid "1 comment"
msgid_plural "@count comments"
msgstr[0] "@count комментарий"
msgstr[1] "@count комментария"
msgstr[2] "@count[2] комментариев"

Использовать @count или %count - зависит от можественной формы исходной строки!

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

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