From bcab5d9c8dc6c5d99b793e044c710a56ae54dce1 Mon Sep 17 00:00:00 2001 From: tony2001 Date: Fri, 18 Jun 2004 15:08:44 +0000 Subject: [PATCH] add translations by Pavel Filippov emdin [at] emdin [dot] ru --- .../advanced-features-objects.xml | 89 ++++--- .../advanced-features-outputfilters.xml | 67 ++--- .../advanced-features-postfilters.xml | 58 ++-- .../advanced-features-prefilters.xml | 53 ++-- .../section-template-cache-handler-func.xml | 100 +++---- .../advanced-features/template-resources.xml | 250 +++++++++--------- 6 files changed, 321 insertions(+), 296 deletions(-) diff --git a/docs/ru/programmers/advanced-features/advanced-features-objects.xml b/docs/ru/programmers/advanced-features/advanced-features-objects.xml index 70b60fe5..1462afa7 100644 --- a/docs/ru/programmers/advanced-features/advanced-features-objects.xml +++ b/docs/ru/programmers/advanced-features/advanced-features-objects.xml @@ -1,75 +1,80 @@ - + - - Objects - - Smarty allows access to PHP objects through the templates. There are - two ways to access them. One way is to register objects to the template, - then use access them via syntax similar to custom functions. The other way - is to assign objects to the templates and access them much like any other - assigned variable. The first method has a much nicer template syntax. It - is also more secure, as a registered object can be restricted to certain - methods or properties. However, a registered object cannot be looped over - or assigned in arrays of objects, etc. The method you choose will be - determined by your needs, but use the first method whenever possible to - keep template syntax to a minimum. - + + + Объекты + + Смарти позволяет использовать в шаблонах объекты PHP. + Существуют два способа их вызова. Первый - зарегистрировать объект для + шаблона, затем вызвать его примерно так же, как и пользовательскую + функцию. Второй - объявить объект для шаблона и использовать его, + как любую другую объявленную переменную. Первый метод гораздо аккуратнее + и безопаснее, так как у зарегистрированного объекта можно ограничить + свойства и методы. Но, в тоже время, зарегистрированный объект + нельзя использовать в циклах, нельзя помещать в массив объектов + и так далее. Выбор способа за вами, но используйте по + возможности первый, чтобы максимально упростить синтаксис шаблона. + - If security is enabled, no private methods or functions can be accessed - (begininning with "_"). If a method and property of the same name exist, - the method will be used. + В безопасном режиме недоступны приватные методы и + функции (имена которых начинаются с "_"). + Если существует и метод, и свойство с одинаковыми именами, + то будет использован метод. - You can restrict the methods and properties that can be accessed by - listing them in an array as the third registration parameter. + Вы можете ограничить использование объекта только некоторыми + методами и свойствами. Для этого перечислите их в массиве и укажите + этот массив третьим параметром при регистрации объекта. - By default, parameters passed to objects through the templates are passed - the same way custom functions get them. An associative array is passed - as the first parameter, and the smarty object as the second. If you want - the parameters passed one at a time for each argument like traditional - object parameter passing, set the fourth registration parameter to false. + По умолчанию, параметры из шаблона передаются объекту точно так же, + как и пользовательской функции. Первым параметром передаётся + ассоциативный массив, вторым - объект Smarty. Если вы хотите передавать + параметры по одному, как при традиционном обращении с объектами, установите + четвёртый параметр вызова в false. - - using a registered or assigned object - + + использование зарегистрированного или объявленного объекта + register_object("foobar",$myobj); -// if we want to restrict access to certain methods or properties, list them +// если мы хотим ограничиться определёнными методами или свойствами, перечисляем их при регистрации $smarty->register_object("foobar",$myobj,array('meth1','meth2','prop1')); -// if you want to use the traditional object parameter format, pass a boolean of false +// если мы хотим использовать традиционный способ передачи параметров объекту, регистрируем объект с соответствующим +// флагом, установленным в false $smarty->register_object("foobar",$myobj,null,false); -// We can also assign objects. Assign by ref when possible. +// Так же мы можем объявить объект. Желательно создавать объект по ссылке. $smarty->assign_by_ref("myobj", $myobj); $smarty->display("index.tpl"); ?> -TEMPLATE: +ШАБЛОН: -{* access our registered object *} +{* вызываем зарегистрированный объект *} {foobar->meth1 p1="foo" p2=$bar} -{* you can also assign the output *} +{* результат можно перегрузить в переменную *} {foobar->meth1 p1="foo" p2=$bar assign="output"} -the output was {$output) +в результате получаем {$output} -{* access our assigned object *} +{* вызываем объявленный объект *} {$myobj->meth1("foo",$bar)} -]]> - +]]> + + \ No newline at end of file +--> diff --git a/docs/ru/programmers/advanced-features/advanced-features-outputfilters.xml b/docs/ru/programmers/advanced-features/advanced-features-outputfilters.xml index 44508162..14f34016 100644 --- a/docs/ru/programmers/advanced-features/advanced-features-outputfilters.xml +++ b/docs/ru/programmers/advanced-features/advanced-features-outputfilters.xml @@ -1,31 +1,31 @@ - + - - Output Filters - - When the template is invoked via display() or fetch(), its output can be - sent through one or more output filters. This differs from postfilters - because postfilters operate on compiled templates before they are saved to - the disk, and output filters operate on the template output when it is - executed. - - - - Output filters can be either - registered or loaded - from the plugins directory by using - load_filter() function or by - setting - $autoload_filters - variable. Smarty will pass the template output as the first argument, - and expect the function to return the result of the processing. - - - using a template outputfilter - + + + Фильтры вывода + + Когда шаблон выводится через display() или fetch(), результат может быть + пропущен через один или несколько фильтров вывода. Отличие их от постфильтров + состоит в том, что постфильтры действуют на уже скомпилированный шаблон, перед + его записью на диск, в то время как фильтры вывода обрабатывают шаблон в момент + его исполнения и результат их применения на диск не записывается. + + + Фильтры вывода могут быть или + зарегистрированы или загружены + из папки с плагинами с помощью + функции load_filter(), + или автоматически вызваны через инициализацию переменной + $autoload_filters. + Smarty передаёт фильтру вывод шаблона в качестве первого параметра. + Предполагается, что функция вернёт обработанный вывод. + + + Использование фильтра вывода + register_outputfilter("protect_email"); $smarty->display("index.tpl"); -// now any occurrence of an email address in the template output will have -// a simple protection against spambots -?> -]]> - +// теперь все адреса электронной почты в выводе шаблона будут +// обработаны несложной функцией защиты от спам-ботов +?>; +]]> + + \ No newline at end of file +--> diff --git a/docs/ru/programmers/advanced-features/advanced-features-postfilters.xml b/docs/ru/programmers/advanced-features/advanced-features-postfilters.xml index 5f4a7e50..d65d6eda 100644 --- a/docs/ru/programmers/advanced-features/advanced-features-postfilters.xml +++ b/docs/ru/programmers/advanced-features/advanced-features-postfilters.xml @@ -1,41 +1,41 @@ - + - - Postfilters - - Template postfilters are PHP functions that your templates are ran through - after they are compiled. Postfilters can be either - registered or loaded - from the plugins directory by using - load_filter() function or by - setting - $autoload_filters - variable. Smarty will pass the compiled template code as the first - argument, and expect the function to return the result of the - processing. - - - using a template postfilter - + + + Постфильтры + + Постфильтры шаблона - это функции PHP, которые обрабатывают шаблон после его компиляции. + Постфильтры могут быть или + зарегистрированы или загружены + из папки с плагинами с помощью + функции load_filter(), + или автоматически вызваны через инициализацию переменной + $autoload_filters. + Smarty передаёт фильтру скомпилированный код шаблона в качестве первого параметра. + Предполагается, что функция вернёт обработанный код. + + + Использование постфильтров + register_postfilter("add_header_comment"); $smarty->display("index.tpl"); -?> +?> -{* compiled Smarty template index.tpl *} -<!-- Created by Smarty! --> -{* rest of template content... *} +{* скомпилированный шаблон index.tpl *} +<!-- Здесь был Смарти --> +{* и дальше прочий код шаблона... *} ]]> - - + + \ No newline at end of file +--> diff --git a/docs/ru/programmers/advanced-features/advanced-features-prefilters.xml b/docs/ru/programmers/advanced-features/advanced-features-prefilters.xml index 1cae4f04..ef4f8095 100644 --- a/docs/ru/programmers/advanced-features/advanced-features-prefilters.xml +++ b/docs/ru/programmers/advanced-features/advanced-features-prefilters.xml @@ -1,40 +1,41 @@ - + - - Prefilters - - Template prefilters are PHP functions that your templates are ran through - before they are compiled. This is good for preprocessing your templates - to remove unwanted comments, keeping an eye on what people are putting - in their templates, etc. Prefilters can be either - registered or loaded from - the plugins directory by using - load_filter() function or by - setting - $autoload_filters variable. - Smarty will pass the template source code as the first argument, and - expect the function to return the resulting template source code. - - - using a template prefilter - + + + Префильтры + + Префильтры шаблона - это функции PHP, которые обрабатывают шаблон перед его компиляцией. + Это удобно для удаления лишних комментариев и прочих ненужных после компиляции данных. + Префильтры могут быть или + заргистрированы или загружены + из папки с плагинами с помощью + функции load_filter(), или + автоматически вызваны через инициализацию переменной + $autoload_filters. + Smarty передаёт фильтру исходный код шаблона в качестве первого параметра. + Предполагается, что функция вернёт обработанный код. + + + Использование префильтра + register_prefilter("remove_dw_comments"); $smarty->display("index.tpl"); ?> -{* Smarty template index.tpl *} -<!--# this line will get removed by the prefilter --> -]]> - +{* шаблон index.tpl *} +<!--# эта строка будет удалена префильтром --> +]]> + + \ No newline at end of file +--> diff --git a/docs/ru/programmers/advanced-features/section-template-cache-handler-func.xml b/docs/ru/programmers/advanced-features/section-template-cache-handler-func.xml index 06f2d3fd..be30ddbc 100644 --- a/docs/ru/programmers/advanced-features/section-template-cache-handler-func.xml +++ b/docs/ru/programmers/advanced-features/section-template-cache-handler-func.xml @@ -1,46 +1,51 @@ - + - - Cache Handler Function - - As an alternative to using the default file-based caching mechanism, you - can specify a custom cache handling function that will be used to read, - write and clear cached files. - - - Create a function in your application that Smarty will use as a - cache handler. Set the name of it in the - $cache_handler_func - class variable. Smarty will now use this to handle cached data. The - first argument is the action, which will be one of 'read', 'write' and - 'clear'. The second parameter is the Smarty object. The third parameter - is the cached content. Upon a write, Smarty passes the cached content - in these parameters. Upon a 'read', Smarty expects your function to - accept this parameter by reference and populate it with the cached - data. Upon a 'clear', pass a dummy variable here since it is not used. - The fourth parameter is the name of the template file (needed for - read/write), the fifth parameter is the cache_id (optional), and the - sixth is the compile_id (optional). - - - example using MySQL as a cache source - + + + Управление кэшированием + + Вместо стандартного механизма кэширования, использующего файлы, + вы можете использовать свои функции для чтения, записи и очистки кэшированных шаблонов. + + + Добавьте в ваше приложение функцию, которую Smarty сможет использовать для + управления кэшем. Укажите её имя в переменной класса + $cache_handler_func. + Теперь Smarty будет использовать её для операций с кэшированным содержимым. + Первый параметр вашей функции - действие, принимает значения + 'read', 'write' или 'clear' (соответственно, 'прочитать', 'записать' + или 'очистить'). Вторым параметром передаётся объект smarty. Третьим - данные для + кэширования. + Третий параметр используется только при чтении и записи. При записи Smarty передаёт + через него кэшированный контент. При чтении предполагается, что через него + передаётся ссылка на переменную, в которую контент будет загружен. + При очистке значение третьего параметра не обрабатывается. + Четвёртый параметр - имя файла с шаблоном (используется при чтении/записи), + пятый - идентификатор кэша (опционально), шестой - идентификатор компиляции (опционально, + используется для построения разных кэшей для одного шаблона), + седьмой - срок годности кэша (опционально). + + Примечание: последний параметр ($exp_time) добавлен в Smarty 2.6.0. + + + Применение MySQL в качестве хранилища кэшированных данных + cache_handler_func = 'mysql_cache_handler'; -$smarty->display('index.tpl'); +$smarty->display('index.tpl'); -mysql database is expected in this format: +код для MySQL таблицы: create database SMARTY_CACHE; @@ -51,32 +56,33 @@ CacheContents MEDIUMTEXT NOT NULL */ -function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null) +function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null, $exp_time=null) { - // set db host, user and pass here + // параметры подключения к базе данных - хост, логин, пароль, название базы $db_host = 'localhost'; $db_user = 'myuser'; $db_pass = 'mypass'; $db_name = 'SMARTY_CACHE'; + // установите в true для использования gzip компрессии кэшированных данных $use_gzip = false; - // create unique cache id + // создаём уникальный идентификатор кэша $CacheID = md5($tpl_file.$cache_id.$compile_id); if(! $link = mysql_pconnect($db_host, $db_user, $db_pass)) { - $smarty_obj->_trigger_error_msg("cache_handler: could not connect to database"); + $smarty_obj->_trigger_error_msg("cache_handler: не могу подключиться к базе данных"); return false; } mysql_select_db($db_name); switch ($action) { case 'read': - // save cache to database + // чтение кэша из базы $results = mysql_query("select CacheContents from CACHE_PAGES where CacheID='$CacheID'"); if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + $smarty_obj->_trigger_error_msg("ошибка кэша: неверный запрос."); } - $row = mysql_fetch_array($results,MYSQL_ASSOC); + $row = mysql_fetch_array($results,MYSQL_ASSOC); if($use_gzip && function_exists("gzuncompress")) { $cache_contents = gzuncompress($row["CacheContents"]); @@ -86,10 +92,10 @@ function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=n $return = $results; break; case 'write': - // save cache to database + // сохранение кэша в базе if($use_gzip && function_exists("gzcompress")) { - // compress the contents for storage efficiency + // сжимаем контент чтобы сэкономить место $contents = gzcompress($cache_content); } else { $contents = $cache_content; @@ -99,12 +105,12 @@ function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=n '".addslashes($contents)."') "); if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + $smarty_obj->_trigger_error_msg("ошибка кэша: неверный запрос."); } $return = $results; break; case 'clear': - // clear cache info + // очистка кэша if(empty($cache_id) && empty($compile_id) && empty($tpl_file)) { // clear them all $results = mysql_query("delete from CACHE_PAGES"); @@ -112,13 +118,13 @@ function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=n $results = mysql_query("delete from CACHE_PAGES where CacheID='$CacheID'"); } if(!$results) { - $smarty_obj->_trigger_error_msg("cache_handler: query failed."); + $smarty_obj->_trigger_error_msg("ошибка кэша: неверный запрос."); } $return = $results; break; default: - // error, unknown action - $smarty_obj->_trigger_error_msg("cache_handler: unknown action \"$action\""); + // ошибка, указан неизвестный метод + $smarty_obj->_trigger_error_msg("ошибка кэша: неизвестный метод \"$action\""); $return = false; break; } @@ -127,7 +133,7 @@ function mysql_cache_handler($action, &$smarty_obj, &$cache_content, $tpl_file=n } -?> +?> ]]> @@ -150,4 +156,4 @@ End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 ---> \ No newline at end of file +--> diff --git a/docs/ru/programmers/advanced-features/template-resources.xml b/docs/ru/programmers/advanced-features/template-resources.xml index 76db7f9f..89c0e478 100644 --- a/docs/ru/programmers/advanced-features/template-resources.xml +++ b/docs/ru/programmers/advanced-features/template-resources.xml @@ -1,107 +1,115 @@ - + - - Resources - - The templates may come from a variety of sources. When you display or - fetch a template, or when you include a template from within another - template, you supply a resource type, followed by the appropriate path - and template name. - - - Templates from $template_dir - - Templates from the $template_dir do not require a template - resource, although you can use the file: resource for consistancy. - Just supply the path to the template you want to use relative to - the $template_dir root directory. - - - using templates from $template_dir - -// from PHP script + + + Ресурсы + + Шаблоны можно получать из самых разных источников. Когда вы отображаете, вызываете + или подключаете один шаблон из другого, вы указываете тип ресурса, вместе с + соответствующим путём и названием шаблона. + + + + Шаблоны из папки $template_dir + + Шаблоны, лежащие в папке $template_dir, не требуют при вызове указания + типа ресурса, хотя вы можете использовать префикс file: для сохранения + стиля. Для вызова просто укажите относительный от $template_dir путь к шаблону. + + + Вызов шаблона из папки $template_dir + +display("index.tpl"); $smarty->display("admin/menu.tpl"); -$smarty->display("file:admin/menu.tpl"); // same as one above +$smarty->display("file:admin/menu.tpl"); // тоже самое, что и строкой выше -{* from within Smarty template *} +{* код в шаблоне *} {include file="index.tpl"} -{include file="file:index.tpl"} {* same as one above *} - - - - Templates from any directory - - Templates outside of the $template_dir require the file: template - resource type, followed by the absolute path and name of the - template. - - - using templates from any directory - -// from PHP script +{include file="file:index.tpl"} {* тоже самое, что и строкой выше *} +]]> + + + + + + Шаблоны из произвольной папки + + Для вызова шаблонов из папки вне $template_dir необходимо + использовать префикс file: с последующим указанием асболютного + пути и имени шаблона. + + + Вызов шаблона из произвольной папки + +display("file:/export/templates/index.tpl"); $smarty->display("file:/path/to/my/templates/menu.tpl"); -{* from within Smarty template *} -{include file="file:/usr/local/share/templates/navigation.tpl"} - - - - Windows Filepaths - - If you are using a Windows machine, filepaths usually include a - drive letter (C:) at the beginning of the pathname. Be sure to use - "file:" in the path to avoid namespace conflicts and get the - desired results. - - - using templates from windows file paths - -// from PHP script +{* код в шаблоне *} +{include file="file:/usr/local/share/templates/navigation.tpl"} +]]> + + + + Пути в Windows + + Если вы работаете под Windows, то пути к файлам, как правило, + начинаются с буквы логического диска (например, C:). Не забудьте + указать префикс "file:" в начале пути, чтобы избежать проблем с именами + и достичь необходимого результата. + + + Вызов шаблона под windows + +display("file:C:/export/templates/index.tpl"); $smarty->display("file:F:/path/to/my/templates/menu.tpl"); -{* from within Smarty template *} -{include file="file:D:/usr/local/share/templates/navigation.tpl"} - - - +{* код в шаблоне *} +{include file="file:D:/usr/local/share/templates/navigation.tpl"} +]]> + + + + - - Templates from other sources - - You can retrieve templates using whatever possible source you can - access with PHP: databases, sockets, LDAP, and so on. You do this - by writing resource plugin functions and registering them with - Smarty. - + + Шаблоны из прочих источников + + Вы можете вызывать шаблоны, используя любые доступные через PHP источники: + базы данных, сокеты, LDAP и так далее. + Для этого нужно написать соответствующий плагин ресурса и зарегистрировать + его для Smarty. + - - See resource plugins - section for more information on the functions you are supposed - to provide. - + + Смотрите раздел плагины ресурсов + для более подробной информации о соответствующих функциях. + - - - Note that you cannot override the built-in - file resource, but you can provide a resource - that fetches templates from the file system in some other way by - registering under another resource name. - - - - using custom resources - + + + Обратите внимание на то, что вы не можете переопределить встроенный ресурс + file, но в ваших силах написать и зарегистрировать ресурс с + другим именем, который будет использовать другой способ вызова шаблонов из + файловой системы. + + + + Использование своих ресурсов + query("select tpl_source from my_table @@ -114,9 +122,9 @@ function db_get_template ($tpl_name, &$tpl_source, &$smarty_obj) } } -function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) +function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) { - // do database call here to populate $tpl_timestamp. + // обращаемся к базе, запрашиваем поле $tpl_timestamp. $sql = new SQL; $sql->query("select tpl_timestamp from my_table @@ -131,65 +139,69 @@ function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj) function db_get_secure($tpl_name, &$smarty_obj) { - // assume all templates are secure + // предполагаем, что наши шаблоны совершенно безопасны return true; } function db_get_trusted($tpl_name, &$smarty_obj) { - // not used for templates + // не используется для шаблонов } -// register the resource name "db" +// регистрируем ресурс "db" $smarty->register_resource("db", array("db_get_template", "db_get_timestamp", "db_get_secure", "db_get_trusted")); -// using resource from php script +// используем ресурс из PHP скрипта $smarty->display("db:index.tpl"); -{* using resource from within Smarty template *} +{* используем ресурс из шаблона *} {include file="db:/extras/navigation.tpl"} -]]> - - +]]> + + + - - Default template handler function - - You can specify a function that is used to retrieve template - contents in the event the template cannot be retrieved from its - resource. One use of this is to create templates that do not exist - on-the-fly. - - - using the default template handler function - -<?php -// put this function somewhere in your application + + Функция для обработки шаблона по умолчанию + + Вы можете определить функцию, которая будет использована, + если шаблон не может быть вызван из соответствующего ресурса. + Это можно использовать, к примеру, для построения недостающего + шаблона на лету. + + + использование функции для обработки шаблона по умолчанию + +_write_file($resource_name,$template_source); return true; } } else { - // not a file + // не файл return false; } } -// set the default handler +// определение обработчика $smarty->default_template_handler_func = 'make_template'; -?> - - +?> +]]> + + + \ No newline at end of file +-->