Надстройки¶
Добавлено в версии 2.19.
Надстройки предоставляют способы настройки рабочего процесса перевода. Они могут быть установлены в виде компонента перевода и работать за кулисами. Управление надстройками доступно для администраторов из меню Управлять ↓ Надстройки соответствующего компонента перевода.
Встроенные надстройки¶
Автоматический перевод¶
Добавлено в версии 3.9.
Автоматически переводит строки при помощи машинного перевода или других компонентов.
Эта надстройка срабатывает автоматически при появлении в компоненте новых строк.
CDN локализации JavaScript’а¶
Добавляет CDN локализации для локализации JavaScript’а или HTML’я.
Его можно использовать для локализации статических HTML-страниц или для загрузки локализации в код JavaScript.
Upon installation the addon generates unique URL for your component which you can include in the HTML documents to get them localized. See Translating HTML and JavaScript using Weblate CDN for more details.
Очистка файлов перевода¶
Обновить все файлы переводов до соответствия одноязычному базовому файлу. Для большинства форматов файлов это означает удаление устарелых ключей переводов, которых больше нет в базовом файле.
Языковая согласованность¶
Убедитесь, что все компоненты в рамках одного проекта переведены на все языки проекта.
Он создает пустые переводы на языках, у которых есть недобавленные компоненты.
Отсутствующие языки проверяются каждые 24 часа и при добавлении нового языка в Weblate.
В отличие от большинства других надстроек, эта влияет на весь проект.
Подсказка
Auto-translate the newly added strings with Автоматический перевод.
Обнаружение компонента¶
Автоматически добавляет или удаляет компоненты проекта, основываясь на изменениях файлов в системе контроля версий.
It is triggered on every VCS update, and otherwise similar to the import_project
management command. This way you can track multiple translation
components within one VCS.
Create one main component least likely to disappear in the future, and others will employ Внутренние URL-адреса Weblate to it as a VCS configuration, and configure it to find all components in it.
The matching is done using regular expressions, where power is a tradeoff for complexity in configuration. Some examples for common use cases can be found in the addon help section.
Once you hit Save, a preview of matching components will be presented, from where you can check whether the configuration actually matches your needs:
См.также
Массовая правка¶
Добавлено в версии 3.11.
Позволяет массово править флаги, метки или состояния для строк.
Automating the labeling of new strings can be useful (start out with search query NOT
has:label
and add desired labels till all strings are properly labeled).
You can also carry out any other automated operations for Weblate metadata.
См.также
Отмечать неизменённые переводы как «На правку»¶
Добавлено в версии 3.1.
При импорте из VCS подлежащей переводу строки и ее совпадении с исходной, она помечается в Weblate как «На правку». Это особенно полезно для файловых форматов, которые включают в себя все строки, даже если они не переведены.
Отмечать новые исходные строки как «На правку»¶
Когда новая исходная строка импортируется из VCS, она помечается как «На правку» в Weblate. Таким образом, вы можете легко фильтровать и править исходные строки, добавленные разработчиками.
Пометить новые переводы как «На правку»¶
При импорте из VCS подлежащей переводу строки она помечается в Weblate как «На правку». Таким образом, вы можете легко фильтровать и редактировать переводы, созданные разработчиками.
Генератор статистики¶
Генерирует файл, содержащий детальную информацию о переводе.
You can use Django template in both filename and content, see Template markup for a detailed markup description.
Например, создание сводного файла для каждого перевода:
- Имя сгенерированного файла
locale/{{ language_code }}.json
- Содержимое
{ "language": "{{ language_code }}", "strings": "{{ stats.all }}", "translated": "{{ stats.translated }}", "last_changed": "{{ stats.last_changed }}", "last_author": "{{ stats.last_author }}", }
См.также
Участники в комментарии¶
Обновлять комментарий в заголовке PO-файла для включения имён участников и лет участия.
Заголовок файла PO будет содержать список внесших вклад и годы участия:
# Michal Čihař <michal@cihar.com>, 2012, 2018, 2019, 2020.
# Pavel Borecki <pavel@example.com>, 2018, 2019.
# Filip Hron <filip@example.com>, 2018, 2019.
# anonymous <noreply@weblate.org>, 2019.
Обновлять переменную ALL_LINGUAS в файле «configure»¶
Updates the ALL_LINGUAS variable in configure
, configure.in
or any
configure.ac
files, when a new translation is added.
Настроить вывод gettext¶
Позволяет настроить поведение вывода gettext, например, заворот строк.
Он предлагает следующие варианты:
Переносить строки длиной 77 символов и у символов перевода строки
Переносить строки только в конце строки
Не переносить строки
Примечание
По умолчанию gettext переносит строки из 77 символов и символы новой строки. С параметром –no-wrap переносится только на символах новой строки.
Обновлять LINGUAS-файл¶
Обновляет LINGUAS-файл при добавлении нового перевода.
Генерировать MO-файлы¶
Автоматически генерирует MO-файл для каждого изменённого PO-файла.
Обновлять PO-файлы до соответствия POT (msgmerge)¶
Обновляет все PO-файлы, используя msgmerge, приводя их в соответствие с POT-файлом. Это происходит всякий раз, когда новые изменения извлекаются из вышестоящего репозитория.
Склеивать Git-коммиты¶
Склеивать Git-коммиты до отправки изменений.
Вы можете выбрать один из следующих режимов:
Добавлено в версии 3.4.
Все коммиты в один
По языку
По файлу
Добавлено в версии 3.5.
По автору
Original commit messages are kept, but authorship is lost unless «Per author» is selected, or the commit message is customized to include it.
Добавлено в версии 4.1.
The original commit messages can optionally be overridden with a custom commit message.
Trailers (commit lines like Co-authored-by: ...
) can optionally be removed
from the original commit messages and appended to the end of the squashed
commit message. This also generates proper Co-authored-by:
credit for every
translator.
Настроить вывод JSON¶
Позволяет подправить поведение вывода JSON, например, отступы или сортировку ключей.
Форматирует файл свойств Java¶
Сортирует файл свойств Java.
Удаление устаревшего комментария¶
Добавлено в версии 3.7.
Устанавливает сроки удаления комментариев.
This can be useful to remove old comments which might have become outdated. Use with care as comment being old does not mean they have lost their importance.
Устаревшее предложение удалено¶
Добавлено в версии 3.7.
Устанавливает сроки удаления предложений.
This can be very useful in connection with suggestion voting (see Коллегиальное рецензирование) to remove suggestions which don’t receive enough positive votes in a given timeframe.
Обновить файлы RESX¶
Добавлено в версии 3.9.
Обновлять все файлы перевода, приводя их в соответствие с одноязычным исходным базовым файлом. Неиспользуемые строки удаляются, а новые добавляются как копии исходных строк.
Подсказка
Use Очистка файлов перевода if you only want to remove stale translation keys.
Настроить вывод YAML¶
Добавлено в версии 3.10.2.
Позволяет подправить поведение вывода YAML, например, длину строк и символы перевода строк.
Customizing list of addons¶
The list of addons is configured by WEBLATE_ADDONS
.
To add another addon, simply include class absolute name in this setting.
Writing addon¶
You can write your own addons too, all you need to do is subclass BaseAddon
,
define the addon metadata and implement a callback which will do the processing.
Here is an example addon:
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
from django.utils.translation import gettext_lazy as _
from weblate.addons.base import BaseAddon
from weblate.addons.events import EVENT_PRE_COMMIT
class ExampleAddon(BaseAddon):
# Filter for compatible components, every key is
# matched against property of component
compat = {"file_format": {"po", "po-mono"}}
# List of events addon should receive
events = (EVENT_PRE_COMMIT,)
# Addon unique identifier
name = "weblate.example.example"
# Verbose name shown in the user interface
verbose = _("Example addon")
# Detailed addon description
description = _("This addon does nothing it is just an example.")
# Callback to implement custom behavior
def pre_commit(self, translation, author):
return
Executing scripts from addon¶
Addons can also be used to execute external scripts. This used to be integrated in Weblate, but now you have to write some code to wrap your script with an addon.
#
# Copyright © 2012 - 2020 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
"""Example pre commit script."""
from django.utils.translation import gettext_lazy as _
from weblate.addons.events import EVENT_PRE_COMMIT
from weblate.addons.scripts import BaseScriptAddon
class ExamplePreAddon(BaseScriptAddon):
# Event used to trigger the script
events = (EVENT_PRE_COMMIT,)
# Name of the addon, has to be unique
name = "weblate.example.pre"
# Verbose name and long descrption
verbose = _("Execute script before commit")
description = _("This addon executes a script.")
# Script to execute
script = "/bin/true"
# File to add in commit (for pre commit event)
# does not have to be set
add_file = "po/{{ language_code }}.po"
For installation instructions see Custom quality checks, addons and auto-fixes.
The script is executed with the current directory set to the root of the VCS repository for any given component.
Additionally, the following environment variables are available:
-
WL_VCS
¶ Version control system used.
-
WL_REPO
¶ Upstream repository URL.
-
WL_PATH
¶ Absolute path to VCS repository.
-
WL_BRANCH
¶ Добавлено в версии 2.11.
Repository branch configured in the current component.
-
WL_FILEMASK
¶ Filemask for current component.
-
WL_TEMPLATE
¶ Filename of template for monolingual translations (can be empty).
-
WL_NEW_BASE
¶ Добавлено в версии 2.14.
Filename of the file used for creating new translations (can be empty).
-
WL_FILE_FORMAT
¶ Fileformat used in current component.
-
WL_LANGUAGE
¶ Language of currently processed translation (not available for component level hooks).
-
WL_PREVIOUS_HEAD
¶ Previous HEAD on update (available only when running post update hook).
-
WL_COMPONENT_SLUG
¶ Добавлено в версии 3.9.
Плашка компонента, используемая для построения URL-адреса.
-
WL_PROJECT_SLUG
¶ Добавлено в версии 3.9.
Плашка проекта, используемая для построения URL-адреса.
-
WL_COMPONENT_NAME
¶ Добавлено в версии 3.9.
Имя компонента.
-
WL_PROJECT_NAME
¶ Добавлено в версии 3.9.
Название проекта.
-
WL_COMPONENT_URL
¶ Добавлено в версии 3.9.
Component URL.
-
WL_ENGAGE_URL
¶ Добавлено в версии 3.9.
Project engage URL.
См.также
Post update repository processing¶
Post update repository processing can be used to update translation files when the VCS upstream source changes. To achieve this, please remember that Weblate only sees files committed to the VCS, so you need to commit changes as a part of the script.
For example with Gulp you can do it using following code:
#! /bin/sh
gulp --gulpfile gulp-i18n-extract.js
git commit -m 'Update source strings' src/languages/en.lang.json
Pre commit processing of translations¶
Use the commit script to automatically make changes to the translation before it is committed to the repository.
It is passed as a single parameter consisting of the filename of a current translation.