Показать страницуИстория страницыСсылки сюдаCopy this pageExport to MarkdownODT преобразованиеНаверх Вы загрузили старую версию документа! Сохранив её, вы создадите новую текущую версию с этим содержимым. Медиафайлы{{tag>web script smarty}} ====== Smarty ====== ===== Переменные ===== <code Smarty> {$foo} отображение простой переменной (не массив и не объект) {$foo[4]} отображает 5-й элемент числового массива {$foo.bar} отображает значение ключа "bar" ассоциативного массива, подобно PHP $foo['bar'] {$foo.$bar} отображает значение переменного ключа массива, подобно PHP $foo[$bar] {$foo->bar} отображает свойство "bar" объекта {$foo->bar()} отображает возвращаемое значение метода "bar" объекта {#foo#} отображает переменную "foo" конфигурационного файла {$smarty.config.foo} синоним для {#foo#} {$foo[bar]} синтаксис доступен только в цикле section, см. {section} {assign var=foo value='baa'}{$foo} отображает "baa", см. {assign} Также доступно множество других комбинаций {$foo.bar.baz} {$foo.$bar.$baz} {$foo[4].baz} {$foo[4].$baz} {$foo.bar.baz[4]} {$foo->bar($baz,2,$bar)} передача параметра {"foo"} статические значения также разрешены {* отображает серверную переменную "SERVER_NAME" ($_SERVER['SERVER_NAME'])*} {$smarty.server.SERVER_NAME} // // Внедренные переменные в двойных кавычках // {func var="test $foo test"} ищет $foo {func var="test $foo_bar test"} ищет $foo_bar {func var="test $foo[0] test"} ищет $foo[0] {func var="test $foo[bar] test"} ищет $foo[bar] {func var="test $foo.bar test"} ищет $foo (не $foo.bar) {func var="test `$foo.bar` test"} ищет $foo.bar {func var="test `$foo.bar` test"|escape} модификатор вне кавычек! // // Примеры // {* заменит $tpl_name её значением *} {include file="subdir/$tpl_name.tpl"} {* не заменит $tpl_name *} {include file='subdir/$tpl_name.tpl'} {* нужны обратные кавычки из за того, что имя содержит точки *} {cycle values="one,two,`$smarty.config.myval`"} {* аналог $module['contact'].'.tpl' в PHP *} {include file="`$module.contact`.tpl"} {* аналог $module[$view].'.tpl' в PHP *} {include file="`$module.$view`.tpl"} </code> * [[http://www.smarty.net/docsv2/ru/language.variables.tpl#id2601705|Подробнее]] ===== Переменные запроса ===== <code Smarty> {* отображение параметра page из URL ($_GET) http://www.example.com/index.php?page=foo *} {$smarty.get.page} {* отображение параметра "page" из формы ($_POST['page']) *} {$smarty.post.page} {* отображение значения cookie "username" ($_COOKIE['username']) *} {$smarty.cookies.username} {* отображение серверной переменной "SERVER_NAME" ($_SERVER['SERVER_NAME'])*} {$smarty.server.SERVER_NAME} {* отображение переменной системного окружения "PATH" *} {$smarty.env.PATH} {* отображение переменной сессии PHP "id" ($_SESSION['id']) *} {$smarty.session.id} {* отображение переменной "username" из смешенных get/post/cookies/server/env *} {$smarty.request.username} </code> * [[http://www.smarty.net/docsv2/ru/language.variables.smarty.tpl#id2602077|Подробнее]] ==== Арифметические операции ==== <code smarty> {$foo+1} {$foo*$bar} {* несколько более сложных примеров *} {$foo->bar-$bar[1]*$baz->foo->bar()-3*7} {if ($foo+$bar.test%$baz*134232+10+$b+10)} {$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"} {assign var="foo" value="`$foo+$bar`"} </code> ==== Модификаторы переменных ==== <code smarty> {* применение модификатора к переменной *} {$title|upper} {* модификатор с параметрами *} {$title|truncate:40:'...'} {* применение модификатора к аргументу функции *} {html_table loop=$myvar|upper} {* с параметрами *} {html_table loop=$myvar|truncate:40:'...'} {* применение модификатора к строке *} {'foobar'|upper} {* использование date_format для форматирования текущей даты *} {$smarty.now|date_format:"%Y/%m/%d"} {* применение модификатора к функции *} {mailto|upper address='smarty@example.com'} {* использование функции PHP str_repeat *} {'='|str_repeat:80} {* функция PHP count *} {$myArray|@count} {* функция PHP shuffle, применяемая к IP адресу сервера *} {$smarty.server.SERVER_ADDR|shuffle} (* это приведет в верхний регистр букв и обрежет пробелы у всех элементов массива *} <select name="name_id"> {html_options output=$myArray|upper|truncate:20} </select> // // Комбинирование модификаторов // {$articleTitle} {$articleTitle|upper|spacify} {$articleTitle|lower|spacify|truncate} {$articleTitle|lower|truncate:30|spacify} {$articleTitle|lower|spacify|truncate:30:". . ."} </code> ==== Условия ==== <code smarty> {if $name eq 'Fred'} Welcome Sir. {elseif $name eq 'Wilma'} Welcome Ma'am. {else} Welcome, whatever you are. {/if} {* пример с логикой "или" *} {if $name eq 'Fred' or $name eq 'Wilma'} ... {/if} {* то же самое, что и выше *} {if $name == 'Fred' || $name == 'Wilma'} ... {/if} {* скобки разрешены *} {if ( $amount < 0 or $amount > 1000 ) and $volume >= #minVolAmt#} ... {/if} {* вы также можете использовать функции php *} {if count($var) gt 0} ... {/if} {* проверка на массив *} {if is_array($foo) } ... {/if} {* проверка на существование *} {if isset($foo) } ... {/if} {* проверяет чётность значений *} {if $var is even} ... {/if} {if $var is odd} ... {/if} {if $var is not odd} ... {/if} {* проверяет, делится ли $var на 4 без остатка *} {if $var is div by 4} ... {/if} {* проверяет, является ли $var чётным двум, например 0=чётно, 1=чётно, 2=нечётно, 3=нечётно, 4=чётно, 5=чётно и т.д. *} {if $var is even by 2} ... {/if} {* 0=чётно, 1=чётно, 2=чётно, 3=нечётно, 4=нечётно, 5=нечётно и т.д. *} {if $var is even by 3} ... {/if} {if isset($name) && $name = 'Blog'} {* сделать что-нибудь *} {elseif $name == $foo} {* сделать что-нибудь другое *} {/if} {if is_array($foo) && count($foo) > 0) {* выполнить цикл foreach *} {/if} </code> * [[http://www.smarty.net/docsv2/ru/language.function.if.tpl#id2622102|Подробнее]] ==== section - Обход массива ==== <code smarty> {* этот пример напечатает все значения массива $custid *} {section name=customer loop=$custid} id: {$custid[customer]}<br /> {/section} {* этот пример напечатает все значения массива $custid в обратном порядке *} {section name=foo loop=$custid step=-1} {$custid[foo]}<br /> {/section} {section name=foo start=10 loop=20 step=2} {$smarty.section.foo.index} {/section} {section name=bar loop=21 max=6 step=-2} {$smarty.section.bar.index} {/section} {* переменная loop определяет только количество итераций. вы можете получать доступ к любой переменной из шаблона внутри секции. Этот пример предполагает, что $custid, $name и $address все являются массивами, содержащими одинаковое количество значений *} {section name=customer loop=$custid} <p> id: {$custid[customer]}<br /> name: {$name[customer]}<br /> address: {$address[customer]} </p> {/section} {* имя секции может быть любым, так как оно используется для обращения к данным в пределах секции *} {section name=anything loop=$custid} <p> id: {$custid[anything]}<br /> name: {$name[anything]}<br /> address: {$address[anything]} </p> {/section} {* секции могут иметь вложенность любой глубины. Используя вложенные секции, вы можете обращаться к сложным структурам данных, таким как многомерные массивы. В этом примере $contact_type[customer] - это массив типов контактов для текущего клиента. *} {section name=customer loop=$custid} <hr> id: {$custid[customer]}<br /> name: {$name[customer]}<br /> address: {$address[customer]}<br /> {section name=contact loop=$contact_type[customer]} {$contact_type[customer][contact]}: {$contact_info[customer][contact]}<br /> {/section} {/section} {* Это пример вывода ассоциативного массива данных внутри секции *} {section name=customer loop=$contacts} <p> name: {$contacts[customer].name}<br /> home: {$contacts[customer].home}<br /> cell: {$contacts[customer].cell}<br /> e-mail: {$contacts[customer].email} </p> {/section} {* выводим результат запроса к БД в таблицу *} <table> <tr><th> </th><th>Name></th><th>Home</th><th>Cell</th><th>Email</th></tr> {section name=co loop=$contacts} <tr> <td><a href="view.php?id={$contacts[co].id}">view<a></td> <td>{$contacts[co].name}</td> <td>{$contacts[co].home}</td> <td>{$contacts[co].cell}</td> <td>{$contacts[co].email}</td> <tr> {/section} </table> {* sectionelse будет выполнена в том случае, если $custid не содержит значений *} {section name=customer loop=$custid} id: {$custid[customer]}<br /> {sectionelse} there are no values in $custid. {/section} {* к вашему сведению, $custid[customer.index] и $custid[customer] означают одно и то же *} {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]}<br /> {/section} {* к вашему сведению, $custid[cus.index] и $custid[cus] означают одно и то же *} <table> <tr> <th>index</th><th>id</th> <th>index_prev</th><th>prev_id</th> <th>index_next</th><th>next_id</th> </tr> {section name=cus loop=$custid} <tr> <td>{$smarty.section.cus.index}</td><td>{$custid[cus]}</td> <td>{$smarty.section.cus.index_prev}</td><td>{$custid[cus.index_prev]}</td> <td>{$smarty.section.cus.index_next}</td><td>{$custid[cus.index_next]}</td> </tr> {/section} </table> {section name=cu loop=$custid start=5 step=2} iteration={$smarty.section.cu.iteration} index={$smarty.section.cu.index} id={$custid[cu]}<br /> {/section} <table> {section name=co loop=$contacts} {if $smarty.section.co.iteration % 5 == 1} <tr><th> </th><th>Name></th><th>Home</th><th>Cell</th><th>Email</th></tr> {/if} <tr> <td><a href="view.php?id={$contacts[co].id}">view<a></td> <td>{$contacts[co].name}</td> <td>{$contacts[co].home}</td> <td>{$contacts[co].cell}</td> <td>{$contacts[co].email}</td> <tr> {/section} </table> {section name=customer loop=$customers} {if $smarty.section.customer.first} <table> <tr><th>id</th><th>customer</th></tr> {/if} <tr> <td>{$customers[customer].id}}</td> <td>{$customers[customer].name}</td> </tr> {if $smarty.section.customer.last} <tr><td></td><td>{$smarty.section.customer.total} customers</td></tr> </table> {/if} {/section} {section name=customer loop=$custid} {$smarty.section.customer.index} id: {$custid[customer]}<br /> {/section} There were {$smarty.section.customer.loop} customers shown above. {* $show_customer_info (true/false) может быть передан из приложения PHP, чтобы определить, необходимо ли отображать секцию *} {section name=customer loop=$custid show=$show_customer_info} {$smarty.section.customer.rownum} id: {$custid[customer]}<br /> {/section} {if $smarty.section.customer.show} the section was shown. {else} the section was not shown. {/if} {section name=customer loop=$custid step=2} {$smarty.section.customer.index} id: {$custid[customer]}<br /> {/section} There were {$smarty.section.customer.total} customers shown above. </code> * [[http://www.smarty.net/docsv2/ru/language.function.section.tpl|Подробнее]] ==== foreach ==== <code smarty> <ul> {foreach from=$myArray item=foo} <li>{$foo}</li> {/foreach} </ul> <ul> {foreach from=$myArray key=k item=v} <li>{$k}: {$v}</li> {/foreach} </ul> <ul> {foreach from=$items key=myId item=i} <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li> {/foreach} </ul> {foreach name=outer item=contact from=$contacts} <hr /> {foreach key=key item=item from=$contact} {$key}: {$item}<br /> {/foreach} {/foreach} {foreach key=cid item=con from=$results} <a href="contact.php?contact_id={$cid}">{$con.name} - {$con.nick}</a><br /> {foreachelse} Ничего не найдено {/foreach} {* The header block is output every five rows *} <table> {foreach from=$items key=myId item=i name=foo} {if $smarty.foreach.foo.index % 5 == 0} <tr><th>Title</th></tr> {/if} <tr><td>{$i.label}</td></tr> {/foreach} </table> {* этот шаблон выведет 0|1, 1|2, 2|3, ... и т.д. *} {foreach from=$myArray item=i name=foo} {$smarty.foreach.foo.index}|{$smarty.foreach.foo.iteration}, {/foreach} {* отображаем "НОВОЕ" напротив первого элемента, иначе id *} <table> {foreach from=$items key=myId item=i name=foo} <tr> <td>{if $smarty.foreach.foo.first}НОВОЕ{else}{$myId}{/if}</td> <td>{$i.label}</td> </tr> {/foreach} </table> {* Добавляем горизонтальную полосу (<hr />) в конце списка *} {foreach from=$items key=part_id item=prod name=products} <a href="#{$part_id}">{$prod}</a>{if $smarty.foreach.products.last}<hr />{else},{/if} {foreachelse} ... content ... {/foreach} {* отображаем количество отображенных строк в конце *} {foreach from=$items key=part_id item=prod name=foo} {$prod.name}<hr/> {if $smarty.foreach.foo.last} <div id="total">{$smarty.foreach.foo.total} предметов</div> {/if} {foreachelse} ... что-то другое ... {/foreach} </code> ==== include ==== <code smarty> // // Функции // {config_load file='colors.conf'} {include file='header.tpl'} {insert file='banner_ads.tpl' title='Smarty - это круто'} {if $logged_in} Welcome, <font color="{#fontColor#}">{$name}!</font> {else} Hi, {$name}! {/if} {include file='footer.tpl' ad=$random_id} // // Параметры // {include file='header.tpl' attrib_name='attrib value'} {include file=#includeFile# title='Smarty is cool'} {html_select_date display_days=yes} {mailto address='smarty@example.com'} <select name='company_id'> {html_options options=$companies selected=$company_id} </select> <html> <head> <title>{$title}</title> </head> <body> {include file='page_header.tpl'} {* тут идёт тело шаблона *} {include file="$tpl_name.tpl"} заменит $tpl_name его значением {include file='page_footer.tpl'} </body> </html> {include file='header.tpl' title='Main Menu' table_bgcolor='#c0c0c0'} {* тут идёт тело шаблона *} {include file='footer.tpl' logo='http://my.example.com/logo.gif'} <body> {include file='nav.tpl' assign=navbar} {include file='header.tpl' title='Main Menu' table_bgcolor='#effeef'} {$navbar} {* тут идёт тело шаблона *} {include file='footer.tpl' logo='http://my.example.com/logo.gif'} {$navbar} </body> {* абсолютные пути *} {include file='/usr/local/include/templates/header.tpl'} {* абсолютные пути (то же самое) *} {include file='file:/usr/local/include/templates/header.tpl'} {* абсолютные пути в windows (ОБЯЗАТЕЛЬНО используйте префикс "file:") *} {include file='file:C:/www/pub/templates/header.tpl'} {* подключение шаблона из ресурса с именем "db" *} {include file='db:header.tpl'} {* подключение шаблона с переменным именем - например, $module = 'contacts' *} {include file="$module.tpl"} {* не будет работать, т.к. в одинарных кавычках не работает подстановка переменных *} {include file='$module.tpl'} </code> * [[http://www.smarty.net/docsv2/ru/language.function.include.tpl#id2622950|Подробнее]] ==== hook ==== <code smarty> {if $page_children} {hook name="pages:page_children"} <ul class="subpages-list"> {foreach from=$page_children item=child_page} <li><span class="main-info">{$child_page.timestamp|date_format:$settings.Appearance.date_format} <a href="{if $child_page.page_type == $smarty.const.PAGE_TYPE_LINK}{$child_page.link}{else}{$index_script}?dispatch=pages.view&page_id={$child_page.page_id}{/if}"{if $child_page.new_window} target="_blank"{/if}>{$child_page.page}</a></span></li> {/foreach} </ul> {/hook} {/if} </code> ==== Наследование шаблонов ==== * http://www.smarty.net/docs/en/advanced.features.template.inheritance.tpl * http://www.smarty.net/docs/en/language.function.extends.tpl * http://www.smarty.net/docs/en/language.function.block.tpl СохранитьПросмотрРазличияОтменить Сводка изменений Примечание: редактируя эту страницу, вы соглашаетесь на использование своего вклада на условиях следующей лицензии: CC0 1.0 Universal