Несколько тегов, разделённых запятой, означают логическое И между ними. Вы также можете использовать точку с запятой в качестве логического ИЛИ. И имеет высший приоритет над ИЛИ. Вы не можете использовать скобки для группировки условий. Звёздочка (*) внутри тега используется в качестве маски для "подстроки".
Разделы: Документация / Расширяем Cotonti / Локализация
Начиная с версии Cotonti 0.9.13 языковые файлы движка совместимы со стандартами сервиса переводов Transifex, ознакомится с проектом и присоединиться к международной команде переводчиков можно здесь:
https://www.transifex.com/projects/p/cotonti/
Для начала работы с сервисом переводов, желательно изучить документацию — Transifex Help Pages (на английском языке). В этой статье будут освещены только особенности касающиеся работы с файлами Cotonti.
После регистрации на сервисе Transifex в качестве пользователя вам будет необходимо запросить доступ в группу перевода одного из языков, или сделать запрос на создание новой группы, если перевода на ваш язык еще нет. После назначения вас в одну из групп перевода вы сможете использовать онлайн интерфейс для перевода файлов.
Кроме онлайн перевода есть возможность скачать набор файлов к себе на диск. О наборе инструментов для «офлайн» перевода далее и пойдет речь.
Все файлы могут быть отредактированы онлайн, тем не менее т.к. Cotonti содержит множество отдельных языковых файлов, для перевода, возможно, будет удобнее скопировать их к себе на диск и использовать свой любимый редактор. Для этого Transifex предоставляет специальную программу работающую с командной строкой — Client tool (далее утилита `tx`).
Внимание! Т.к. часть утилит для автоматизации перевода поставляется в виде скриптов на языке Python, то вам, возможно, потребуется установленный в системе интерпретатор Python (для unix систем он обычно установлен по умолчанию). Скачать его можно здесь: http://python.org/download/. Если вы работаете под ОС Windows, то вам будет полезным настроить команды быстрого вызова — см. инструкцию (на англ. языке).
После этого вы можете установить программу 'tx' (см. английскую инструкцию).
Для облегчения работы по переводу мы подготовили набор утилит для манипуляций с языковыми файлами, скачать которые можно здесь: https://github.com/trustmaster/cotlang. Это набор скриптов на Python, запускаемых из командной строки.
Сервис Transifex работает по аналогии с репозиториями git, поэтому первое что необходимо сделать это получить рабочую копию.
Примечание: все последующие команды подразумевают использование командной строки.
Создайте для работы новый каталог (для примера назовем его 'cot-lang') и перейдите в него, введя в командной строке:
cd cot-lang
Теперь надо инициализировать в этом каталоге репозиторий Transifex командой:
tx init
После этого надо импортировать файл конфигурации. Выполняем:
tx set --auto-remote https://www.transifex.com/projects/p/cotonti/
Для правильного сопоставления файлов локализации Transifex и языковых файлов Cotonti, откройте файл '.tx/config', созданный предыдущей командой и замените его содержимое актуальными настройками для Cotonti из файла:
https://raw.github.com/trustmaster/cotlang/master/tx.config
Замечание для продвинутых пользователей: подобный файл конфигурации может быть создан скриптом 'cotlangtx.py', указав путь к каталогу с исходными файлами Cotonti:
python cotlangtx.py ~/htdocs/cotonti
Теперь пора скопировать языковые файлы в рабочий каталог:
tx pull -a
Отлично. Теперь у вас есть структура каталогов в расположенными в них языковыми файлами.
Если файлы вашей локализации были установлены с версией младше 0.9.13, вам необходимо провести их обновление для соответствия форматам используемым в Transifex. Для этого в наборе утилит cotlang есть скрипт под именем 'cotlangfix.py'. Он автоматизирует 95% работы по изменению файлов. Запускается он следующим образом:
python cotlangfix.py путь/к/исходным/файлам
Он выводит информацию о процессе конвертации на экран. Он так же сообщит о том какие строки должны быть исправлены самостоятельно. Ниже несколько примеров.
Transifex не поддерживает записи разбитые на несколько строк. Поэтому их надо объединить в одну строку. Если перенос строк необходим внутри записи, используйте двойные кавычки и символ \n внутри строки. Не забудьте при замене одинарных кавычек на двойные экранировать символы '$', чтобы они выглядели так '\$'.
Пример, строку:
$L['multiline_example'] = 'это пример %1$s многострочной записи';
Придется заменить на:
$L['multiline_example'] = "это пример\n%1\$s многострочной\nзаписи";
В некоторых случаях в языковых файлах можно встретить записи содержащие переводы вариантов настроек в таком виде:
$L['cfg_array_params'] = array( 'Foo', 'Bar' );
или в таком виде:
$L['cfg_array2_params'] = array( 'foo' => 'Foo', 'bar' => 'Bar' );
Их тоже надо преобразовать в простые строки. Массивы «склеиваются» с помощью знака ',', а ассоциативные массивы собираются в таком виде: 'key1: value1, key2: value2'. Таким образом строки представленные выше преобразуются в следующий вид
$L['cfg_array_params'] = 'Foo, Bar';
и
$L['cfg_array2_params'] = 'foo: Foo, bar: Bar';
Перед загрузкой файлов с переводом на новый язык, убедитесь, что запись для этого языка создана и отображается в проекте Cotonti на сайте Transifex. Если этого языка еще нет в проекте, то войдите на сервис под своей учетной записью (регистрация здесь) и запросите добавление нового языка в проект Cotonti. Мы получим ваш запрос и оперативно создадим запись для новой локализации.
В наборе утилит cotlang есть скрипт под названием 'cotlangcp.py'. Он позволяет упростить операции по копированию набора языковых файлов из одной папки в другую, сохраняя при этом структуру каталогов. Используйте его следующим образом:
python cotlangcp.py путь/к/исходным/файлам путь/к/целевому/каталогу
Кроме этого можно копировать файлы только для определенного языка, например 'nl' (для обозначения используется 2-х буквенный код принятый в Cotonti):
python cotlangcp.py путь/к/исходным/файлам путь/к/целевому/каталогу -l nl
Например, если вы используете текущую 'nl' локализацию, файлы которой находятся в каталоге '~/htdocs/cotonti' и вы хотите скопировать её в каталог репозитория '~/cot-lang', используйте cotlangcp.py следующим образом:
python cotlangcp.py ~/htdocs/cotonti ~/cot-lang -l nl
Теперь, когда у вас есть новые файлы для языка вы можете отправить их на сервер Transifex:
tx push -t -l nl
Замените код 'nl' на код вашего языка.
После этого языковые записи попадут на сервер и будут доступны на страницах проекта https://www.transifex.com/projects/p/cotonti/.
Языковые файлы периодически обновляются. Какие-то строки могут быть добавлены, какие-то удалены. Если вы используете веб-интерфейс Transifex для перевода проблем возникнуть не должно — все изменения видны, просто найти записи без перевода. Более того при редактировании онлайн доступны такие инструменты как Translation Memory и автоматический перевод при помощи сервиса Google.
Тем не менее, вам может потребоваться получить актуальную версию локальной копии языковых файлов для редактирования в привычном редакторе. Сделать это не сложно, с помощью командной строки и все тех же утилит.
Перед внесением любых изменений в файлы лучше всегда обновить локальные копии свежими версиями с сервера:
tx pull
Для получения всех файлов, включая новые используйте команду:
tx pull -a
Теперь вы можете редактировать файлы прямо в текущих каталогах. Или можете скопировать ваш вариант локализации из другой папки, например так:
python cotlangcp.py ~/htdocs/cotonti ~/cot-lang -l nl
Эта команда скопирует языковые файлы голландской локали ('nl')из каталога ~/htdocs/cotonti в каталог ~/cot-lang. Здесь предполагается что каталог ~/cot-lang это каталог вашего Transifex репозитория, а ~/htdocs/cotonti путь где вы храните последние версии файлов с голландской локализацией.
И наоборот, вы всегда можете скопировать последние версии файлов из репозитория Transifex в каталог с файлами вашего сайта на Cotonti:
python cotlangcp.py ~/cot-lang ~/htdocs/cotonti -l nl
Когда процесс редактирования файлов в локальной копии закончен надо отправить изменения на сервер Transifex:
tx push -t -l nl
Замените код 'nl' на соответствующий вашему языку.
Это правило многим должно быть знакомо по работе с Git, однако Tx это не Git, и надо быть более осторожным. Рекомендуем выполнять команда в следующем порядке:
tx pull -a # получаем последнюю версию с сайта cotlangcp.py # редактируем или заменяем часть файлов tx push -t # выгружаем изменения обратно на сервер
Разделы: Documentation / Extending Cotonti / Localizations
Once Cotonti is translated, it is important to keep your own localizations updated as there may be changes or additions to all the language strings from time to time. This article will show you several ways to keep language files up to date.
The most recent code changes always can be found in Cotonti's Git repository. If you have further knowledge in working with version management, you can install Git on your local machine and also commit your translations directly to the repository so that it can be included as a part of the official Cotonti download pakage. Please contact the developers for more information.
Less experienced users could use the GitHub interface instead. GitHub provides a comparison tool to visualice changes between different versions. A link to these comparisons can be found on every Cotonti release notes page (example: code changes from 0.9.4 to 0.9.5), see Files changed tab.
When Cotonti's development was managed through a Trac interface, there was a nice text-based comparison format called unified diff. Git and GitHub still provide this comparison method, but viewing many code changes in a web browser sometimes can be a pain. And people who just wish to manage a localization might not wish to deal with versioning systems. However, there is a simple way to bring back the unified diffs. Here's what to do:
Now you have an unified diff which you can use to apply all necessary changes to your localization. Simply use the editors search functionality to quickly jump to all language related changes. Search for "en.lang" to jump to the comparison part related to all english files for example. A "-" in the old file part means something was changed or removed, a "+" in the new file indicates an addition or change to one or more lines. Please see diff manual for further information and options to create the diff.
Or use a grafical tool like WinMerge for side-by-side comparison.
Once you use Cotonti with predominantly core modules, you can utilize supported Transifex service to maintain you language files up to date. Transifex is 3rd party service for translation purposes. We use it to manage our language files bundled with Cotonti Siena.
With help of Transifex Web UI you can translate Cotonti language files to you language, be notified on files updates with new versions and get info for untranslated resources. To take part in translation process — just register on Transifex (it's free), select language and apply as a translator.
Разделы: Documentation / Extending Cotonti / Localizations
Since v.0.9.13 Cotonti's language files are compatible with Transifex translation service and you can join our international translations teams there:
https://www.transifex.com/projects/p/cotonti/
Please read Transifex Help Pages to get started with the service. In this document we will only cover some topics specific to Cotonti.
After registration as Transifex user you can join our translation team. You would be able to join for some language subteams or request for creation a new language pack. After you'll be approved as a translator you can use online web-interface of Trtansifex to translate files or download a pack of it to translate it offline with your preferred editor.
Below you can read how to setup tools for proper «offline» translation.
You can edit everything online but as Cotonti has plenty of language files, in many cases it would be more comfortable to copy files on your disk and edit them with your favorite editor. For such a case Transifex has a console Client tool.
Python interpreter is requried to use the client tools. If you don't have one, get it from http://python.org/download/. If you are using Windows, setting some shortcuts would be handy too.
Then you can install Transifex 'tx' tool as described in this section.
We also maintain a set of helper tools to manipulate language files easier in this repo: https://github.com/trustmaster/cotlang. They are also written in Python and run in command line.
Transifex works much like a git repository, so what you'd probably like to do first is to checkout yourself a working copy.
First, make a new folder, e.g. called 'cot-lang' and enter it in the command line:
cd cot-lang
Then initialize a Transifex repo in it:
tx init
After doing so, import repository configuration using this command:
tx set --auto-remote https://www.transifex.com/projects/p/cotonti/
To map Transifex translations to Cotonti langfiles correctly, open '.tx/config' file that the previous command created for you and replace all of its contents with the actual Cotonti configuration for Transifex:
https://raw.github.com/trustmaster/cotlang/master/tx.config
Note for advanced users: contents of this file were generated by 'cotlangtx.py' tool given current Cotonti source tree as an argument, e.g.:
python cotlangtx.py ~/htdocs/cotonti
Now you can pull all the existing langfiles to your working copy:
tx pull -a
Done, you now have a source tree with only language files in it.
If you have an existing locale prior to 0.9.13, you should update it to be compatible with Transifex. There is a tool in cotlang package called 'cotlangfix.py' for it. It automates 95% of the fixes that need to be applied. Invoke it this way:
python cotlangfix.py path/to/source
It will print the results on screen. It will also print some strings that should be fixed manually. Below are some common cases.
Transifex does not support strings that have line breaks in them. So you will have to merge them into a single line. To include line breaks though, you need to make sure the strings is in double quotes and then you can replace line breaks with \n. Also when changing from single quotes to double quotes, the '$' character needs to be escaped, so it becomes '\$'. For example,
$L['multiline_example'] = 'Here is some %1$s entry with multiple lines';
should become
$L['multiline_example'] = "Here is\nsome %1\$s entry\nwith multiple lines";
You might also come across a few cases when values for some configuration option are localized like this:
$L['cfg_array_params'] = array( 'Foo', 'Bar' );
or like this:
$L['cfg_array2_params'] = array( 'foo' => 'Foo', 'bar' => 'Bar' );
They should become just a simple string too. So arrays are glued with ',' and associative arrays are glued this way: 'key1: value1, key2: value2'. So above examples become
$L['cfg_array_params'] = 'Foo, Bar';
and
$L['cfg_array2_params'] = 'foo: Foo, bar: Bar';
Before uploading files for a new locale, make sure this locale is already registered and listed with Cotonti project on Transifex. If it's not, log into Transifex and request adding a new language to Cotonti. We will accept your request and create a new locale shortly.
There's a tool in the cotlang set called 'cotlangcp.py' which simplifies copying language files here and there a lot. It copies just the language files and keeps the directory structure. You can use it to copy all language files from one folder to another:
python cotlangcp.py path/to/source path/to/destination
or you can even tell it to copy only language files for a specific locale, e.g. 'nl':
python cotlangcp.py path/to/source path/to/destination -l nl
So, if you have an existing localization e.g. for the 'nl' locale in path '~/htdocs/cotonti' and you want to copy it to '~/cot-lang' repo, you can do it using cotlangcp.py this way:
python cotlangcp.py ~/htdocs/cotonti ~/cot-lang -l nl
Now that you have copied new translation files, you can add and push them to the Transifex server:
tx push -t -l nl
Replace 'nl' in the above examples with your locale code.
At this point your locale should be already on server and you should see it filled in https://www.transifex.com/projects/p/cotonti/.
Language files get updated from times to times. There may be new strings to be translated and some strings may be removed if they are not needed anymore. With Transifex you can monitor all these changes online and find strings to be translated. The online editing is pretty self-explaining and it has some advanced tools like Translation Memory and Automatic Translation via Google. But you might also want to keep your local copy of all locales up2date and use your favorite editor to translate files. No problem, let's use command line tools for it.
It is always good to pull fresh files from server before doing any changes:
tx pull
To pull everything, including new files, run this instead:
tx pull -a
Then you can edit files directly in the current source tree. Or you can copy updated files for your locale from other location, e.g.:
python cotlangcp.py ~/htdocs/cotonti ~/cot-lang -l nl
This command copies 'nl' locale files from ~/htdocs/cotonti folder to ~/cot-lang folder, assuming that ~/cot-lang is your Transifex repo copy and ~/htdocs/cotonti is where you keep the latest langfiles for 'nl' locale.
And vice versa, you can copy the latest files from the Transifex repo to your Cotonti site using the same cotlangcp.py tool:
python cotlangcp.py ~/cot-lang ~/htdocs/cotonti -l nl
When you are done with translating a portion of files in the Transifex repo copy, you can push your changes to the server:
tx push -t -l nl
Replace 'nl' with your locale code.
This rule comes from git, but tx is not git so you need to be more careful. Normally you should do it in this order:
tx pull -a # get a fresh copy cotlangcp.py # modify or copy updated files tx push -t # push your updated translation
Разделы: Documentation (Genoa and older) / English / Skins
<?PHP
/**
* YOUR-LANGUAGE Language File for YOUR-SKIN-NAME Skin
*
* @package Cotonti
* @version COTONTI VERSION
* @author YOUR NAME
* @copyright YOUR COPYRIGHT
* @license BSD
*/
defined('SED_CODE') or die('Wrong URL.');
?>
<?PHP
/**
* English Language File for Sed-Light Skin
*
* @package Cotonti
* @version 0.1.0
* @author Cotonti Translators Team
* @copyright Copyright (c) Cotonti Team 2008-2009
* @license BSD
*/
defined('SED_CODE') or die('Wrong URL.');
?>
defined('SED_CODE') or die('Wrong URL.');
?>
$variable['variable_name] = 'variable_text';
$skinlang['Comment'] = 'Your comment';
{PHP.variable.variable_name}
{PHP.skinlang.Comment}
$skinlang['Comment'] = 'Your comment';
$skinlang['Comment'] = 'Ваш комментарий';