add translations by Pavel Filippov emdin [at] emdin [dot] ru

This commit is contained in:
tony2001
2004-06-18 15:08:44 +00:00
parent 2b8687804b
commit bcab5d9c8d
6 changed files with 321 additions and 296 deletions
@@ -1,75 +1,80 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="advanced.features.objects">
<title>Objects</title>
<para>
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.
</para>
<!-- EN-Revision: 1.1 -->
<sect1 id="advanced.features.objects">
<title>Объекты</title>
<para>
Смарти позволяет использовать в шаблонах объекты PHP.
Существуют два способа их вызова. Первый - зарегистрировать объект для
шаблона, затем вызвать его примерно так же, как и пользовательскую
функцию. Второй - объявить объект для шаблона и использовать его,
как любую другую объявленную переменную. Первый метод гораздо аккуратнее
и безопаснее, так как у зарегистрированного объекта можно ограничить
свойства и методы. Но, в тоже время, зарегистрированный объект
нельзя использовать в циклах, нельзя помещать в массив объектов
и так далее. Выбор способа за вами, но используйте по
возможности первый, чтобы максимально упростить синтаксис шаблона.
</para>
<para>
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.
В безопасном режиме недоступны приватные методы и
функции (имена которых начинаются с "_").
Если существует и метод, и свойство с одинаковыми именами,
то будет использован метод.
</para>
<para>
You can restrict the methods and properties that can be accessed by
listing them in an array as the third registration parameter.
Вы можете ограничить использование объекта только некоторыми
методами и свойствами. Для этого перечислите их в массиве и укажите
этот массив третьим параметром при регистрации объекта.
</para>
<para>
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.
</para>
<example>
<title>using a registered or assigned object</title>
<programlisting role="php">
<example>
<title>использование зарегистрированного или объявленного объекта</title>
<programlisting role="php">
<![CDATA[
<?php
// the object
// сам объект
class My_Object() {
function meth1($params, &$smarty_obj) {
return "this is my meth1";
return "это мой метод meth1";
}
}
$myobj = new My_Object;
// registering the object (will be by reference)
// регистрируем объект (будет доступен по ссылке)
$smarty->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)}
]]></programlisting>
</example>
]]>
</programlisting>
</example>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
@@ -90,4 +95,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->
@@ -1,31 +1,31 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="advanced.features.outputfilters">
<title>Output Filters</title>
<para>
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.
</para>
<para>
Output filters can be either
<link linkend="api.register.outputfilter">registered</link> or loaded
from the plugins directory by using
<link linkend="api.load.filter">load_filter()</link> function or by
setting
<link linkend="variable.autoload.filters">$autoload_filters</link>
variable. Smarty will pass the template output as the first argument,
and expect the function to return the result of the processing.
</para>
<example>
<title>using a template outputfilter</title>
<programlisting>
<!-- EN-Revision: 1.1 -->
<sect1 id="advanced.features.outputfilters">
<title>Ôèëüòðû âûâîäà</title>
<para>
Êîãäà øàáëîí âûâîäèòñÿ ÷åðåç display() èëè fetch(), ðåçóëüòàò ìîæåò áûòü
ïðîïóùåí ÷åðåç îäèí èëè íåñêîëüêî ôèëüòðîâ âûâîäà. Îòëè÷èå èõ îò ïîñòôèëüòðîâ
ñîñòîèò â òîì, ÷òî ïîñòôèëüòðû äåéñòâóþò íà óæå ñêîìïèëèðîâàííûé øàáëîí, ïåðåä
åãî çàïèñüþ íà äèñê, â òî âðåìÿ êàê ôèëüòðû âûâîäà îáðàáàòûâàþò øàáëîí â ìîìåíò
åãî èñïîëíåíèÿ è ðåçóëüòàò èõ ïðèìåíåíèÿ íà äèñê íå çàïèñûâàåòñÿ.
</para>
<para>
Ôèëüòðû âûâîäà ìîãóò áûòü èëè
<link linkend="api.register.outputfilter">çàðåãèñòðèðîâàíû</link> èëè çàãðóæåíû
èç ïàïêè ñ ïëàãèíàìè ñ ïîìîùüþ
ôóíêöèè <link linkend="api.load.filter">load_filter()</link>,
èëè àâòîìàòè÷åñêè âûçâàíû ÷åðåç èíèöèàëèçàöèþ ïåðåìåííîé
<link linkend="variable.autoload.filters">$autoload_filters</link>.
Smarty ïåðåäà¸ò ôèëüòðó âûâîä øàáëîíà â êà÷åñòâå ïåðâîãî ïàðàìåòðà.
Ïðåäïîëàãàåòñÿ, ÷òî ôóíêöèÿ âåðí¸ò îáðàáîòàííûé âûâîä.
</para>
<example>
<title>Èñïîëüçîâàíèå ôèëüòðà âûâîäà</title>
<programlisting>
<![CDATA[
&lt;?php
// put this in your application
<?php
// êîä â âàøåì ñêðèïòå
function protect_email($tpl_output, &$smarty)
{
$tpl_output =
@@ -34,15 +34,16 @@ function protect_email($tpl_output, &$smarty)
return $tpl_output;
}
// register the outputfilter
// ðåãèñòðàöèÿ ôèëüòðà âûâîäà
$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
?&gt;
]]></programlisting>
</example>
// òåïåðü âñå àäðåñà ýëåêòðîííîé ïî÷òû â âûâîäå øàáëîíà áóäóò
// îáðàáîòàíû íåñëîæíîé ôóíêöèåé çàùèòû îò ñïàì-áîòîâ
?>;
]]>
</programlisting>
</example>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
@@ -63,4 +64,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->
@@ -1,41 +1,41 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="advanced.features.postfilters">
<title>Postfilters</title>
<para>
Template postfilters are PHP functions that your templates are ran through
after they are compiled. Postfilters can be either
<link linkend="api.register.postfilter">registered</link> or loaded
from the plugins directory by using
<link linkend="api.load.filter">load_filter()</link> function or by
setting
<link linkend="variable.autoload.filters">$autoload_filters</link>
variable. Smarty will pass the compiled template code as the first
argument, and expect the function to return the result of the
processing.
</para>
<example>
<title>using a template postfilter</title>
<programlisting>
<!-- EN-Revision: 1.1 -->
<sect1 id="advanced.features.postfilters">
<title>Ïîñòôèëüòðû</title>
<para>
Ïîñòôèëüòðû øàáëîíà - ýòî ôóíêöèè PHP, êîòîðûå îáðàáàòûâàþò øàáëîí ïîñëå åãî êîìïèëÿöèè.
Ïîñòôèëüòðû ìîãóò áûòü èëè
<link linkend="api.register.postfilter">çàðåãèñòðèðîâàíû</link> èëè çàãðóæåíû
èç ïàïêè ñ ïëàãèíàìè ñ ïîìîùüþ
ôóíêöèè <link linkend="api.load.filter">load_filter()</link>,
èëè àâòîìàòè÷åñêè âûçâàíû ÷åðåç èíèöèàëèçàöèþ ïåðåìåííîé
<link linkend="variable.autoload.filters">$autoload_filters</link>.
Smarty ïåðåäà¸ò ôèëüòðó ñêîìïèëèðîâàííûé êîä øàáëîíà â êà÷åñòâå ïåðâîãî ïàðàìåòðà.
Ïðåäïîëàãàåòñÿ, ÷òî ôóíêöèÿ âåðí¸ò îáðàáîòàííûé êîä.
</para>
<example>
<title>Èñïîëüçîâàíèå ïîñòôèëüòðîâ</title>
<programlisting>
<![CDATA[
&lt;?php
// put this in your application
<?php
// êîä â âàøåì ñêðèïòå
function add_header_comment($tpl_source, &$smarty)
{
return "&lt;?php echo \"&lt;!-- Created by Smarty! --&gt;\n\" ?&gt;\n".$tpl_source;
return "&lt;?php echo \"&lt;!-- Çäåñü áûë Ñìàðòè --&gt;\n\" ?&gt;\n".$tpl_source;
}
// register the postfilter
// ðåãèñòðàöèÿ ïîñòôèëüòðà
$smarty->register_postfilter("add_header_comment");
$smarty->display("index.tpl");
?&gt;
?>
{* compiled Smarty template index.tpl *}
&lt;!-- Created by Smarty! --&gt;
{* rest of template content... *}
{* ñêîìïèëèðîâàííûé øàáëîí index.tpl *}
&lt;!-- Çäåñü áûë Ñìàðòè --&gt;
{* è äàëüøå ïðî÷èé êîä øàáëîíà... *}
]]>
</programlisting>
</example>
</programlisting>
</example>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
@@ -56,4 +56,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->
@@ -1,40 +1,41 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="advanced.features.prefilters">
<title>Prefilters</title>
<para>
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
<link linkend="api.register.prefilter">registered</link> or loaded from
the plugins directory by using
<link linkend="api.load.filter">load_filter()</link> function or by
setting
<link linkend="variable.autoload.filters">$autoload_filters</link> variable.
Smarty will pass the template source code as the first argument, and
expect the function to return the resulting template source code.
</para>
<example>
<title>using a template prefilter</title>
<programlisting>
<!-- EN-Revision: 1.1 -->
<sect1 id="advanced.features.prefilters">
<title>Ïðåôèëüòðû</title>
<para>
Ïðåôèëüòðû øàáëîíà - ýòî ôóíêöèè PHP, êîòîðûå îáðàáàòûâàþò øàáëîí ïåðåä åãî êîìïèëÿöèåé.
Ýòî óäîáíî äëÿ óäàëåíèÿ ëèøíèõ êîììåíòàðèåâ è ïðî÷èõ íåíóæíûõ ïîñëå êîìïèëÿöèè äàííûõ.
Ïðåôèëüòðû ìîãóò áûòü èëè
<link linkend="api.register.prefilter">çàðãèñòðèðîâàíû</link> èëè çàãðóæåíû
èç ïàïêè ñ ïëàãèíàìè ñ ïîìîùüþ
ôóíêöèè <link linkend="api.load.filter">load_filter()</link>, èëè
àâòîìàòè÷åñêè âûçâàíû ÷åðåç èíèöèàëèçàöèþ ïåðåìåííîé
<link linkend="variable.autoload.filters">$autoload_filters</link>.
Smarty ïåðåäà¸ò ôèëüòðó èñõîäíûé êîä øàáëîíà â êà÷åñòâå ïåðâîãî ïàðàìåòðà.
Ïðåäïîëàãàåòñÿ, ÷òî ôóíêöèÿ âåðí¸ò îáðàáîòàííûé êîä.
</para>
<example>
<title>Èñïîëüçîâàíèå ïðåôèëüòðà</title>
<programlisting>
<![CDATA[
<?php
// put this in your application
// êîä â âàøåì ñêðèïòå
function remove_dw_comments($tpl_source, &$smarty)
{
return preg_replace("/&lt;!--#.*--&gt;/U","",$tpl_source);
}
// register the prefilter
// ðåãèñòðàöèÿ ïðåôèëüòðà
$smarty->register_prefilter("remove_dw_comments");
$smarty->display("index.tpl");
?>
{* Smarty template index.tpl *}
&lt;!--# this line will get removed by the prefilter --&gt;
]]></programlisting>
</example>
{* øàáëîí index.tpl *}
&lt;!--# ýòà ñòðîêà áóäåò óäàëåíà ïðåôèëüòðîì --&gt;
]]>
</programlisting>
</example>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
@@ -55,4 +56,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->
@@ -1,46 +1,51 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="section.template.cache.handler.func">
<title>Cache Handler Function</title>
<para>
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.
</para>
<para>
Create a function in your application that Smarty will use as a
cache handler. Set the name of it in the
<link linkend="variable.cache.handler.func">$cache_handler_func</link>
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).
</para>
<example>
<title>example using MySQL as a cache source</title>
<programlisting>
<!-- EN-Revision: 1.1 -->
<sect1 id="section.template.cache.handler.func">
<title>Управление кэшированием</title>
<para>
Вместо стандартного механизма кэширования, использующего файлы,
вы можете использовать свои функции для чтения, записи и очистки кэшированных шаблонов.
</para>
<para>
Добавьте в ваше приложение функцию, которую Smarty сможет использовать для
управления кэшем. Укажите её имя в переменной класса
<link linkend="variable.cache.handler.func">$cache_handler_func</link>.
Теперь Smarty будет использовать её для операций с кэшированным содержимым.
Первый параметр вашей функции - действие, принимает значения
'read', 'write' или 'clear' (соответственно, 'прочитать', 'записать'
или 'очистить'). Вторым параметром передаётся объект smarty. Третьим - данные для
кэширования.
Третий параметр используется только при чтении и записи. При записи Smarty передаёт
через него кэшированный контент. При чтении предполагается, что через него
передаётся ссылка на переменную, в которую контент будет загружен.
При очистке значение третьего параметра не обрабатывается.
Четвёртый параметр - имя файла с шаблоном (используется при чтении/записи),
пятый - идентификатор кэша (опционально), шестой - идентификатор компиляции (опционально,
используется для построения разных кэшей для одного шаблона),
седьмой - срок годности кэша (опционально).
Примечание: последний параметр ($exp_time) добавлен в Smarty 2.6.0.
</para>
<example>
<title>Применение MySQL в качестве хранилища кэшированных данных</title>
<programlisting>
<![CDATA[
&lt;?php
<?php
/*
example usage:
пример использования:
include('Smarty.class.php');
include('mysql_cache_handler.php');
$smarty = new Smarty;
$smarty-&gt;cache_handler_func = 'mysql_cache_handler';
$smarty->cache_handler_func = 'mysql_cache_handler';
$smarty-&gt;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-&gt;_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-&gt;_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-&gt;_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-&gt;_trigger_error_msg("cache_handler: query failed.");
$smarty_obj->_trigger_error_msg("ошибка кэша: неверный запрос.");
}
$return = $results;
break;
default:
// error, unknown action
$smarty_obj-&gt;_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
}
?&gt;
?>
]]></programlisting>
</example>
</sect1>
@@ -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
-->
-->
@@ -1,107 +1,115 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<sect1 id="template.resources">
<title>Resources</title>
<para>
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.
</para>
<sect2 id="templates.from.template.dir">
<title>Templates from $template_dir</title>
<para>
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.
</para>
<example>
<title>using templates from $template_dir</title>
<programlisting>
// from PHP script
<!-- EN-Revision: 1.1 -->
<sect1 id="template.resources">
<title>Ðåñóðñû</title>
<para>
Øàáëîíû ìîæíî ïîëó÷àòü èç ñàìûõ ðàçíûõ èñòî÷íèêîâ. Êîãäà âû îòîáðàæàåòå, âûçûâàåòå
èëè ïîäêëþ÷àåòå îäèí øàáëîí èç äðóãîãî, âû óêàçûâàåòå òèï ðåñóðñà, âìåñòå ñ
ñîîòâåòñòâóþùèì ïóò¸ì è íàçâàíèåì øàáëîíà.
</para>
<sect2 id="templates.from.template.dir">
<title>Øàáëîíû èç ïàïêè $template_dir</title>
<para>
Øàáëîíû, ëåæàùèå â ïàïêå $template_dir, íå òðåáóþò ïðè âûçîâå óêàçàíèÿ
òèïà ðåñóðñà, õîòÿ âû ìîæåòå èñïîëüçîâàòü ïðåôèêñ file: äëÿ ñîõðàíåíèÿ
ñòèëÿ. Äëÿ âûçîâà ïðîñòî óêàæèòå îòíîñèòåëüíûé îò $template_dir ïóòü ê øàáëîíó.
</para>
<example>
<title>Âûçîâ øàáëîíà èç ïàïêè $template_dir</title>
<programlisting>
<![CDATA[
// PHP ñêðèïò
$smarty->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 *}</programlisting>
</example>
</sect2>
<sect2 id="templates.from.any.dir">
<title>Templates from any directory</title>
<para>
Templates outside of the $template_dir require the file: template
resource type, followed by the absolute path and name of the
template.
</para>
<example>
<title>using templates from any directory</title>
<programlisting>
// from PHP script
{include file="file:index.tpl"} {* òîæå ñàìîå, ÷òî è ñòðîêîé âûøå *}
]]>
</programlisting>
</example>
</sect2>
<sect2 id="templates.from.any.dir">
<title>Øàáëîíû èç ïðîèçâîëüíîé ïàïêè</title>
<para>
Äëÿ âûçîâà øàáëîíîâ èç ïàïêè âíå $template_dir íåîáõîäèìî
èñïîëüçîâàòü ïðåôèêñ file: ñ ïîñëåäóþùèì óêàçàíèåì àñáîëþòíîãî
ïóòè è èìåíè øàáëîíà.
</para>
<example>
<title>Âûçîâ øàáëîíà èç ïðîèçâîëüíîé ïàïêè</title>
<programlisting>
<![CDATA[
// PHP ñêðèïò
$smarty->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"}</programlisting>
</example>
<sect3>
<title>Windows Filepaths</title>
<para>
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.
</para>
<example>
<title>using templates from windows file paths</title>
<programlisting>
// from PHP script
{* êîä â øàáëîíå *}
{include file="file:/usr/local/share/templates/navigation.tpl"}
]]>
</programlisting>
</example>
<sect3>
<title>Ïóòè â Windows</title>
<para>
Åñëè âû ðàáîòàåòå ïîä Windows, òî ïóòè ê ôàéëàì, êàê ïðàâèëî,
íà÷èíàþòñÿ ñ áóêâû ëîãè÷åñêîãî äèñêà (íàïðèìåð, C:). Íå çàáóäüòå
óêàçàòü ïðåôèêñ "file:" â íà÷àëå ïóòè, ÷òîáû èçáåæàòü ïðîáëåì ñ èìåíàìè
è äîñòè÷ü íåîáõîäèìîãî ðåçóëüòàòà.
</para>
<example>
<title>Âûçîâ øàáëîíà ïîä windows</title>
<programlisting>
<![CDATA[
// PHP ñêðèïò
$smarty->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"}</programlisting>
</example>
</sect3>
</sect2>
{* êîä â øàáëîíå *}
{include file="file:D:/usr/local/share/templates/navigation.tpl"}
]]>
</programlisting>
</example>
</sect3>
</sect2>
<sect2 id="templates.from.elsewhere">
<title>Templates from other sources</title>
<para>
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.
</para>
<sect2 id="templates.from.elsewhere">
<title>Øàáëîíû èç ïðî÷èõ èñòî÷íèêîâ</title>
<para>
Âû ìîæåòå âûçûâàòü øàáëîíû, èñïîëüçóÿ ëþáûå äîñòóïíûå ÷åðåç PHP èñòî÷íèêè:
áàçû äàííûõ, ñîêåòû, LDAP è òàê äàëåå.
Äëÿ ýòîãî íóæíî íàïèñàòü ñîîòâåòñòâóþùèé ïëàãèí ðåñóðñà è çàðåãèñòðèðîâàòü
åãî äëÿ Smarty.
</para>
<para>
See <link linkend="plugins.resources">resource plugins</link>
section for more information on the functions you are supposed
to provide.
</para>
<para>
Ñìîòðèòå ðàçäåë <link linkend="plugins.resources">ïëàãèíû ðåñóðñîâ</link>
äëÿ áîëåå ïîäðîáíîé èíôîðìàöèè î ñîîòâåòñòâóþùèõ ôóíêöèÿõ.
</para>
<note>
<para>
Note that you cannot override the built-in
<literal>file</literal> resource, but you can provide a resource
that fetches templates from the file system in some other way by
registering under another resource name.
</para>
</note>
<example>
<title>using custom resources</title>
<programlisting>
<note>
<para>
Îáðàòèòå âíèìàíèå íà òî, ÷òî âû íå ìîæåòå ïåðåîïðåäåëèòü âñòðîåííûé ðåñóðñ
<literal>file</literal>, íî â âàøèõ ñèëàõ íàïèñàòü è çàðåãèñòðèðîâàòü ðåñóðñ ñ
äðóãèì èìåíåì, êîòîðûé áóäåò èñïîëüçîâàòü äðóãîé ñïîñîá âûçîâà øàáëîíîâ èç
ôàéëîâîé ñèñòåìû.
</para>
</note>
<example>
<title>Èñïîëüçîâàíèå ñâîèõ ðåñóðñîâ</title>
<programlisting>
<![CDATA[
// from PHP script
// PHP ñêðèïò
// put these function somewhere in your application
function db_get_template ($tpl_name, &amp;$tpl_source, &amp;$smarty_obj)
// êîä â âàøåì ñêðèïòå
function db_get_template ($tpl_name, &$tpl_source, &$smarty_obj)
{
// do database call here to fetch your template,
// populating $tpl_source
// îáðàùàåìñÿ ê áàçå, çàïðàøèâàåì êîä øàáëîíà,
// ïåðåãðóæàåì åãî â $tpl_source
$sql = new SQL;
$sql->query("select tpl_source
from my_table
@@ -114,9 +122,9 @@ function db_get_template ($tpl_name, &amp;$tpl_source, &amp;$smarty_obj)
}
}
function db_get_timestamp($tpl_name, &amp;$tpl_timestamp, &amp;$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, &amp;$tpl_timestamp, &amp;$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"}
]]></programlisting>
</example>
</sect2>
]]>
</programlisting>
</example>
</sect2>
<sect2 id="default.template.handler.function">
<title>Default template handler function</title>
<para>
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.
</para>
<example>
<title>using the default template handler function</title>
<programlisting>
&lt;?php
// put this function somewhere in your application
<sect2 id="default.template.handler.function">
<title>Ôóíêöèÿ äëÿ îáðàáîòêè øàáëîíà ïî óìîë÷àíèþ</title>
<para>
Âû ìîæåòå îïðåäåëèòü ôóíêöèþ, êîòîðàÿ áóäåò èñïîëüçîâàíà,
åñëè øàáëîí íå ìîæåò áûòü âûçâàí èç ñîîòâåòñòâóþùåãî ðåñóðñà.
Ýòî ìîæíî èñïîëüçîâàòü, ê ïðèìåðó, äëÿ ïîñòðîåíèÿ íåäîñòàþùåãî
øàáëîíà íà ëåòó.
</para>
<example>
<title>èñïîëüçîâàíèå ôóíêöèè äëÿ îáðàáîòêè øàáëîíà ïî óìîë÷àíèþ</title>
<programlisting>
<![CDATA[
<?php
// êîä â âàøåì ñêðèïòå
function make_template ($resource_type, $resource_name, &amp;$template_source, &amp;$template_timestamp, &amp;$smarty_obj)
function make_template ($resource_type, $resource_name, &$template_source, &$template_timestamp, &$smarty_obj)
{
if( $resource_type == 'file' ) {
if ( ! is_readable ( $resource_name )) {
// create the template file, return contents.
$template_source = "This is a new template.";
// ñîçäà¸ì è çàïèñûâàåì ôàéë øàáëîíà.
$template_source = "Ýòî íîâûé øàáëîí.";
$template_timestamp = time();
$smarty_obj->_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';
?&gt;</programlisting>
</example>
</sect2>
?>
]]>
</programlisting>
</example>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
@@ -210,4 +222,4 @@ End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
-->