Files
smarty/docs/ru/appendixes/tips.xml
2004-04-14 15:29:09 +00:00

367 lines
9.4 KiB
XML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?xml version="1.0" encoding="windows-1251"?>
<!-- $Revision$ -->
<chapter id="tips">
<title>Советы</title>
<sect1 id="tips.blank.var.handling">
<title>Обработка пустых переменных</title>
<para>
Иногда, например, для того чтобы фон таблицы работал корректно,
необходимо вывести вместо пустого значения переменной, значение
по умолчанию "&amp;nbsp;". Многие бы использовали конструкцию {if},
но есть более короткий путь в Smatry используя <emphasis>default</emphasis>
модификатор переменной.
</para>
<example>
<title>Вывод &amp;nbsp;, если переменная пуста</title>
<programlisting>
<![CDATA[
{* длинный путь *}
{if $title eq ""}
&nbsp;
{else}
{$title}
{/if}
{* короткий путь *}
{$title|default:"&nbsp;"}
]]>
</programlisting>
</example>
</sect1>
<sect1 id="tips.default.var.handling">
<title>Обработка переменных по умлочанию</title>
<para>
Если переменная встречается часто, то использование модификатора
default каждый раз можно избежать, используя функцию
<link linkend="language.function.assign">assign</link>.
</para>
<example>
<title>Назначение переменной шаблона значения по умолчанию</title>
<programlisting>
<![CDATA[
{* вверху шаблона *}
{assign var="title" value=$title|default:"no title"}
{* если переменная $title была пустой, то сейчас она содержит "no title" *}
{$title}
]]>
</programlisting>
</example>
</sect1>
<sect1 id="tips.passing.vars">
<title>Присвоение переменной заголовка (title) заголовку шаблона.</title>
<para>
Если большинство ваших шаблонов имеют похожие верхние и нижние
части, то имеет смысл вынести их в отдельные файлы. Но если
шапка должна иметь различные заголовки на различных страницах?
Смотрите пример ниже.
</para>
<example>
<title>Присвоение переменной заголовка (title) заголовку шаблона.</title>
<programlisting>
<![CDATA[
mainpage.tpl
------------
{include file="header.tpl" title="Main Page"}
{* тело шаблона *}
{include file="footer.tpl"}
archives.tpl
------------
{config_load file="archive_page.conf"}
{include file="header.tpl" title=#archivePageTitle#}
{* тело шаблонаe *}
{include file="footer.tpl"}
header.tpl
----------
<HTML>
<HEAD>
<TITLE>{$title|default:"BC News"}</TITLE>
</HEAD>
<BODY>
footer.tpl
----------
</BODY>
</HTML>
]]>
</programlisting>
</example>
<para>
Если выводится главная страница, то заголовок будет "Main Page",
если архивы, то заголовк берется из файла конфигурации. Если
заголовок будет пустой, то выведется значение по умолчанию "BC News".
</para>
</sect1>
<sect1 id="tips.dates">
<title>Даты</title>
<para>
Обычно даты в Smarty всегда передаются как временные метки, что
позволяет проектировщикам шаблонов использовать <link
linkend="language.modifier.date.format">date_format</link>
для полного контроля над форматированием даты и также делает легким
сравнение дат там, где это необходимо.
</para>
<para>
ЗАМЕЧАНИЕ: Начиная с версии Smarty 1.4.0 вы можете передавать дату в виде
временной метки Unix (Unix timestamp), временной метки MySQL или в любом
другом виде, который подерживается функцией PHP strtotime().
</para>
<example>
<title>Использование date_format</title>
<programlisting>
<![CDATA[
{$startDate|date_format}
ВЫВОД:
Jan 4, 2001
{$startDate|date_format:"%Y/%m/%d"}
ВЫВОД:
2001/01/04
{if $date1 < $date2}
...
{/if}
]]></programlisting>
</example>
<para>
Когда {html_select_date} используется в шаблоне, программистам может
понадобиться получить дату виде временной метки. Вот функция, которая поможет это
сделать.
</para>
<example>
<title>Преобразование элементов формы ввода даты назад к временной метке</title>
<programlisting>
<![CDATA[
// Предполагается, что ваши элементы формы названы
// startDate_Day, startDate_Month, startDate_Year
$startDate = makeTimeStamp($startDate_Year,$startDate_Month,$startDate_Day);
function makeTimeStamp($year="",$month="",$day="")
{
if(empty($year))
$year = strftime("%Y");
if(empty($month))
$month = strftime("%m");
if(empty($day))
$day = strftime("%d");
return mktime(0,0,0,$month,$day,$year);
}
]]>
</programlisting>
</example>
</sect1>
<sect1 id="tips.wap">
<title>WAP/WML</title>
<para>
WAP/WML шаблоны требуют, чтобы заголовок Content-type был
передан вместе с шаблоном. Простейший путь - написать
пользовательскую функцию, которая будет выводить заголовки.
Так как мы будем пользоваться тэгами insert, то заголовки не будут
кэшироваться. Так же ничего не должно выводиться в браузер до
шаблона, иначе заголовки могут быть неправильно восприняты.
</para>
<example>
<title>Использование insert для записи WML Content-Type заголовков</title>
<programlisting>
<![CDATA[
// поместите эту функцию в приложение, или в Smarty.addons.php
function insert_header() {
// this function expects $content argument
extract(func_get_arg(0));
if(empty($content))
return;
header($content);
return;
}
// шаблон ДОЛЖЕН начинаться с тэга insert. Пример:
{insert name=header content="Content-Type: text/vnd.wap.wml"}
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<!-- begin new wml deck -->
<wml>
<!-- begin first card -->
<card>
<do type="accept">
<go href="#two"/>
</do>
<p>
Welcome to WAP with Smarty!
Press OK to continue...
</p>
</card>
<!-- begin second card -->
<card id="two">
<p>
Pretty easy isn't it?
</p>
</card>
</wml>
]]>
</programlisting>
</example>
</sect1>
<sect1 id="tips.componentized.templates">
<title>Составные шаблоны</title>
<para>
This tip is a bit of a hack, but still a neat idea. Use at your own
risk. ;-)
</para>
<para>
Traditionally, programming templates into your applications goes as
follows: First, you accumulate your variables within your PHP
application, (maybe with database queries.) Then, you instantiate your
Smarty object, assign the variables and display the template. So lets
say for example we have a stock ticker on our template. We would
collect the stock data in our application, then assign these variables
in the template and display it. Now wouldn't it be nice if you could
add this stock ticker to any application by merely including the
template, and not worry about fetching the data up front?
</para>
<para>
You can embed PHP into your templates with the {php}{/php} tags.
With this, you can setup self contained templates with their own
data structures for assigning their own variables. With the logic
embedded like this, you can keep the template &amp; logic together. This
way no matter where the template source is coming from, it is always
together as one component.
</para>
<example>
<title>componentized template</title>
<programlisting>
<![CDATA[
{* Smarty *}
{php}
// setup our function for fetching stock data
function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
// put logic here that fetches $ticker_name
// and $ticker_price from some resource
}
// call the function
fetch_ticker("YHOO",$ticker_name,$ticker_price);
// assign template variables
$this->assign("ticker_name",$ticker_name);
$this->assign("ticker_price",$ticker_price);
{/php}
Stock Name: {$ticker_name} Stock Price: {$ticker_price}
]]></programlisting>
</example>
<para>
As of Smarty 1.5.0, there is even a cleaner way. You can include php in
your templates with the {include_php ...} tag. This way you can keep
your PHP logic separated from the template logic. See the <link
linkend="language.function.include.php">include_php</link> function for
more information.
</para>
<example>
<title>componentized template with include_php</title>
<programlisting>
<![CDATA[
load_ticker.php
---------------
&lt;?php
// setup our function for fetching stock data
function fetch_ticker($symbol,&$ticker_name,&$ticker_price) {
// put logic here that fetches $ticker_name
// and $ticker_price from some resource
}
// call the function
fetch_ticker("YHOO",$ticker_name,$ticker_price);
// assign template variables
$this->assign("ticker_name",$ticker_name);
$this->assign("ticker_price",$ticker_price);
?&gt;
index.tpl
---------
{* Smarty *}
{include_php file="load_ticker.php"}
Stock Name: {$ticker_name} Stock Price: {$ticker_price}
]]></programlisting>
</example>
</sect1>
<sect1 id="tips.obfuscating.email">
<title>Obfuscating E-mail Addresses</title>
<para>
Do you ever wonder how your E-mail address gets on so many spam mailing
lists? One way spammers collect E-mail addresses is from web pages. To
help combat this problem, you can make your E-mail address show up in
scrambled javascript in the HTML source, yet it it will look and work
correctly in the browser. This is done with the mailto plugin.
</para>
<example>
<title>Example of Obfuscating an E-mail Address</title>
<programlisting>
<![CDATA[
index.tpl
---------
Send inquiries to
{mailto address=$EmailAddress encode="javascript" subject="Hello"}
]]>
</programlisting>
</example>
<note>
<title>Technical Note</title>
<para>
This method isn't 100% foolproof. A spammer could conceivably program his
e-mail collector to decode these values, but not likely.
</para>
</note>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->