User Tools

Site Tools


ru:plugins:i18n

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
Last revision Both sides next revision
ru:plugins:i18n [2013/10/09 11:10]
Arkady created
ru:plugins:i18n [2013/10/09 11:26]
Arkady [Multi-language Front-end]
Line 15: Line 15:
 </​code>​ </​code>​
  
-If your plugin also supports ​GetSimple 2.03, you would rather have to use:+Если ваш плагин поддерживает и GetSimple 2.03, используйте следующий код:
  
 <​code>​ <​code>​
Line 22: Line 22:
 </​code>​ </​code>​
  
-A (not necessarily up-to-date) list of the built in i18n hashes can be found [[i18nhashes|on this page]]. ​ Always check the source for the latest. 
  
-If you need additional texts not found in the standard GetSimple translation filesyou need to create translation files yourselfThey should look like the GetSimple translation filese.g. de_DE.php:+Список встроенных в систему ключей для перевода со значениями можно найти [[i18nhashes|на этой странице]]хотя он не всегда соответствует текущей версииСамая актуальная версия содержитсяконечно,​ в исходниках GetSimple. 
 + 
 +Если вы хотите добавить в файл перевода собственные ключи, отсутствующие в файлах GetSimple, добавьте их в свой языковой файл с переводом самостоятельно,​ например,​ для русского языка (ru_RU.php) это будет выглядеть так:
  
 <​code>​ <​code>​
 $i18n = array( $i18n = array(
-  '​BTN_SAVEMYSETTINGS'​ => 'Meine Einstellungen speichern', +  '​BTN_SAVEMYSETTINGS'​ => 'Моя кнопка для сохранения изменений', 
-  '​MYHEADER'​ => 'Meine Uberschrift'+  '​MYHEADER'​ => 'Мой заголовок'
 ); );
 </​code>​ </​code>​
  
-Put all your plugin specific language files into the directory ''​my_plugin/lang/''​thus giving you a plugin with the following files:+Все языковые файлы размещаются в директории //​мой_плагин/lang///структура файлов плагина должна выглядеть следующим образом:
  
 <​code>​ <​code>​
-my_plugin.php +мой_плагин.php 
-my_plugin ​(directory+мой_плагин ​(директория
-   - .htaccess (with one line: Deny from all)+   - .htaccess (с одной строкой: Deny from all)
    - lang (directory) ​    - lang (directory) ​
-      - .htaccess (with one line: Deny from all)+      - .htaccess (с одной строкой: Deny from all)
       - en_US.php       - en_US.php
-      - de_DE.php +      - de_DE.php ​(если есть такой файл) 
-      - it_IT.php+      - ru_RU.php
 </​code>​ </​code>​
  
-GetSimple 3.0 makes it easy to load these texts in your plugin, e.g.: +Начиная с версии ​GetSimple 3.0 строки перевода из языкового файла легко подгружаются с помощью следующего кода
 <​code>​ <​code>​
-i18n_merge('​my_plugin') || i18n_merge('​my_plugin','​en_US'​);​+i18n_merge('​мой_плагин') || i18n_merge('​мой_плагин ​','​en_US'​);​
 </​code>​ </​code>​
  
-This will try to get the translations for the current admin languageand - if this fails - load the english textsYou need to make sure that the default language (here ''​en_US''​) texts do existe.g. ''​my_plugin/​lang/​en_US.php''​.+Система пытается получить перевод для текущего языка системыустановленного в  административной панели в GetSimpleЕсли попытка не удаетсято загружаются строки из английского языкового файла вашего плагинаРазумеется,​ такой файл для английского языка по умолчанию под именем en_US.php должен находиться в папке ​''​Мой_плагин/​lang/​en_US.php'' ​вашего плагина.
  
-You then access them in the same way as standard ​GetSimple ​textsbut add your plugin name as prefix to the key, e.g.+Доступ к языковому файлу вашего плагина очень похож на стандартный код ​GetSimple ​для такого случаявы только должны добавить наименование плагина как префикс к ключу:
  
 <​code>​ <​code>​
-<input type="​submit"​ name="​save"​ value="<?​php i18n("my_plugin/​BTN_SAVEMYSETTINGS"​);​ ?>"/>​+<input type="​submit"​ name="​save"​ value="<?​php i18n("мой_плагин/​BTN_SAVEMYSETTINGS"​);​ ?>"/>​
 </​code>​ </​code>​
  
-Note that //​i18n()// ​echos the translation If you need to use the translated text in php code you will have to use //​i18n_r()// ​to return the string rather than echoing ite.g.+Обратите внимание,​ что функция ​//​i18n()// ​выводит результат перевода на экранЕсли вам необходимо использовать переведенный текст в PHP-коде,​ используйте функцию ​//​i18n_r()//, ​которая возвращает переведенную строку,​ например:​
  
 <​code>​ <​code>​
-$msg = '<​div style="​display:​ block;"​ class="​updated">'​ . i18n_r("​my_plugin/​MSG_UPDATED"​) . '​.</​div>';​+$msg = '<​div style="​display:​ block;"​ class="​updated">'​ . i18n_r("​мой_плагин/​MSG_UPDATED"​) . '​.</​div>';​
 echo $msg; echo $msg;
 </​code>​ </​code>​
  
-That's itJust provide at least one language file (preferably english - ''​en_US''​and wait for the community to provide translations into other languagesthen include them in your plugin.+Вот как-то такС плагином достаточно поставлять хотя бы один языковой файл ​(разумеется,​ лучше английскийи спокойно ждатьпока кто-то из сообщества не сделает перевод на другой язык. После этого можете включать новый языковой файл в состав своего плагина.
  
  
-===== Language files without country ​=====+===== Языковые файлы без кода страны ​=====
  
-If you want to provide language files en.php, de.php, ​etc(without country code)than use the following lines to load your texts:+Если вы в плагине применяете языковые файлы без кода страны,​ т.е. ​en.php, de.php, ​и.т.д., используйте для подгрузки перевода следующий код:
  
 <​code>​ <​code>​
 global $LANG; global $LANG;
-i18n_merge('​my_plugin', substr($LANG,​0,​2)) || i18n_merge('​my_plugin','​en'​);​+i18n_merge('​мой_плагин', substr($LANG,​0,​2)) || i18n_merge('​мой_плагин','​en'​);​
 </​code>​ </​code>​
  
-===== Front-end ===== 
  
-If your plugin has to display texts on the front-end (the internet site itself) and you just support typical GetSimple installations,​ where the content is displayed in one language and the admin back-end is set to this language, you do it the same way as described above. 
  
-The only difference is that you must provide language supportbecause where it might be acceptable for administrators and editors to see some information in english instead of their own languageit is unacceptable on the front-endWithout language support you basically limit your plugin to use in countries with the same language as your's.+===== Фронтенд ===== 
 + 
 +Если ваш плагин выводит текстовую информацию непосредственно на страницы сайта при типовой установке GetSimpleв случае когда контент сайта и язык административной панели совпадаютработают методы,​ уже описанные в настоящей секции. 
 + 
 +Тем не менее – языковая поддержка должна быть обеспечена. Возможно,​ для администраторов или пользователей с правами редактора допустимо использование администраторского интерфейса на неродном языке (как правило,​ на английском). Но отсутствие поддержки плагином других языков во фронтенде недопустимо. Без мультиязычной поддержки вы практически ставите серьезную преграду для распространения вашего плагина среди пользователей,​ которые не владеют вашим родным языком.
  
 **GetSimple 3.0:** **GetSimple 3.0:**
  
-In the frontend the variable ​$LANG is always ​en_US (due to the multi-user capabilities introduced with 3.0). The user should be encouraged to enter a line +Во фронтенде значение переменной ​$LANG всегда равно ​en_US (из-за многопользовательского функционала,​ внедренного в версии ​3.0+).  ​Пользователю следует указать на необходимость добавить строку 
 + 
 <​code>​ <​code>​
-$LANG = '​de_DE';​+$LANG = 'de_DE'; или, в нашем случае,​ $LANG = 'ru_RU';
 </​code>​ </​code>​
-or similar into gsconfig.php. + 
-As an alternative the plugin can offer a functionality to set the frontend language.+в файл ​gsconfig.php. 
 + 
 +В качестве альтернативы плагин может предлагать пользователю возможность для смены языка сайта.
  
 ===== Multi-language Front-end ===== ===== Multi-language Front-end =====
  
-Some internet sites implemented with GetSimple ​support multiple languagesThe language is determined from the user's preferences ​(his operating system language resp. the browser languageand he might be allowed to switch between the supported languages.+На некоторых интернет-сайтах,​ созданных с помощью ​GetSimple, реализована поддержка нескольких языковЯзык сайта определяется на основе предпочтений пользователя ​(язык операционной системы,​ язык браузера), посетитель имеет возможность переключаться с одного языка на другой.
  
-As multi-language sites are not supported natively by GetSimple, there currently exists one plugin, ​[[http://​get-simple.info/​extend/​plugin/​i18n/​69/​|I18N]].+Создание и управление многоязычными сайтами не поддерживаются ядром ​GetSimple. В настоящее время для решения этой ​ задачи существует единственный плагин ​[[http://​get-simple.info/​extend/​plugin/​i18n/​69/​|I18N]]. ​ 
  
-If your plugin should support multi-language sites using the I18N pluginyou must load the texts **only after the I18N initialization** (in the pretemplate ​hook- in your function(s) that output text on the front endwith+Если ваш плагин должен поддерживать мультиязычные сайты с использованием плагина ​I18N, тексты из языковых фалов вашего плагина  ​**должны загружаются только после инициализации ​I18N** (это происходит в хуке ​pretemplate), ​с помощью следующего кода:
  
 <​code>​ <​code>​
 global $LANG; global $LANG;
 if (function_exists('​i18n_load_texts'​)) { if (function_exists('​i18n_load_texts'​)) {
-  i18n_load_texts('​my_plugin');+  i18n_load_texts('​мой_плагин');
 } else {  ​ } else {  ​
-  i18n_merge('​my_plugin', substr($LANG,​0,​2)) || i18n_merge('​my_plugin', '​en'​);​+  i18n_merge('​мой_плагин', substr($LANG,​0,​2)) || i18n_merge('​мой_плагин', '​en'​);​
 } }
 </​code>​ </​code>​
  
-If you need back end template texts directly when loading the pluginyou need to check, if the plugin is loaded in the backend:+Если при загрузке плагина в административную панель вам сразу требуются языковые строки - необходима проверказагружен ли плагин в бэкенде.
  
 <​code>​ <​code>​
 if (basename($_SERVER['​PHP_SELF'​]) != '​index.php'​) { // back end only - or do you know a better condition? if (basename($_SERVER['​PHP_SELF'​]) != '​index.php'​) { // back end only - or do you know a better condition?
-  i18n_merge('​my_plugin', substr($LANG,​0,​2)) || i18n_merge('​my_plugin', '​en'​);​+  i18n_merge('​мой_плагин', substr($LANG,​0,​2)) || i18n_merge('​мой_плагин', '​en'​);​
 } }
-add_action('​plugins-sidebar',​ '​createSideMenu',​ array($thisfile,​ i18n_r('​my_plugin/​CONFIGURE'​))); ​+add_action('​plugins-sidebar',​ '​createSideMenu',​ array($thisfile,​ i18n_r('​мой_плагин/​CONFIGURE'​))); ​
 </​code>​ </​code>​
  
-This code will work (with GetSimple 3.0+), ​whether the I18N plugin is present or not.+Этот код будет работать ​(с GetSimple 3.0+) вне зависимости от тогоустановлен ли в системе плагин ​I18N или нет. 
 + 
 +**На заметку**:​ функция i18n_load_texts доступна в версиях плагина I18N 1.0+.
  
-Notethe function i18n_load_texts is available in the I18N plugin 1.0+.+**На заметку**На текущий момент плагин ​I18N поддерживает только языковые коды без наименования страны,​ таким образом,​ языковым файлам должны присваиваться имена ''​en.php'',​ ''​de.php'',​ и пр., ​ а не ''​en_US.php'',​ и.т.д.
  
-Note: The I18N plugin currently only supports language codes without country, so you must have language files like ''​en.php'',​ ''​de.php''​ etc. instead of ''​en_US.php'',​ etc. 
  
  
ru/plugins/i18n.txt · Last modified: 2013/10/09 12:23 by Arkady