Необходимый минимум по SMARTY

В smarty предусмотрено комментирование кода?

{* комментарий *}

Как экранировать код в котором встречаются {}

{ldelim} = {, {rdelim} = }

либо

{literal}…{/literal}

Как посчитать количество элементов в массиве

{$group.items|@count}

Как создать внутреннюю переменную smarty

{assign var=tmp_var value=»string value»}

Значение переменной по-умолчанию

{$my_var|default:»Default value»}

Как сделать чтобы смарти вычислил значение переменной при присвоении

{include file=»`$evaluable_variable`/shell_header.inc»}
{include file=»$cpp/shell_header.inc»}

{include file=»$template/index.tpl»}

так не сработает — {include file=»$prefixindex.tpl»}

{$include file=$prefix|concat:»index.tpl»}

Полезные строковые модификаторы

{$cart_content[index].cost|replace:’&’:’&’}
{$mystring|substr:5:10}
{$mystring|substr:5}

Экранирование

{$articleTitle|escape}
{$articleTitle|escape:’html’} {* экранирует & » ‘ < > *}
{$articleTitle|escape:’htmlall’} {* экранирует ВСЕ HTML-сущности *}
{$articleTitle|escape:’url’}
{$articleTitle|escape:’quotes’}

Текущая дата

{$smarty.now|date_format:»%d.%m.%Y %H:%M»}

Как организовать цикл for

for($i=1;$i<10;$i++) {section name=foo loop=9} {$smarty.section.foo.iteration} {/section} Как в цикле foreach определить первый и последний элемент {foreach name=foo from=$array} {if $smarty.foreach.foo.first} этот первый {/if} {$smarty.foreach.foo|@debug_print_var} {if $smarty.foreach.foo.last} этот последний {/if} {/foreach} Использование условий if {if isset($name) && NOT empty($name)} ... {elseif $name == $foo} ... {/if} {if is_array($foo) && count($foo) > 0)
{* do a foreach loop *}
{/if}

Передача параметров вызываемому шаблону

{include file=’navigator.tpl’ params=$params}

В шаблоне navigator.tpl будет доступна переменная $params с переданным значением.

Использование захватов (capture)

{capture name=capMe}
I am html
{/capture}

{if $some_expression_is_true}
{$smarty.capture.capMe}
{else}

{$smarty.capture.capMe}
{/if}

Смарти умеет вычислять!

{math equation=»(( x + y ) / z )» x=2 y=10 z=2}
{math equation=»x + y» x=4.4444 y=5.0000 format=»%.2f»}
{math equation=»height * width / division»
height=$row_height
width=$row_width
division=$div}

Случайное число

(random)

{math equation=’rand(10,100)’}

Дополнительные вспомогательные операции

% mod $a mod $b modulus %
is [not] div by $a is not div by 4 divisible by $a % $b == 0
is [not] even $a is not even [not] an even number (unary) $a % 2 == 0
is [not] even by $a is not even by $b grouping level [not] even ($a / $b) % 2 == 0
is [not] odd $a is not odd [not] an odd number (unary) $a % 2 != 0
is [not] odd by $a is not odd by $b [not] an odd grouping ($a / $b) % 2 != 0

#модуль, определение четности, нечетности, кратности

Переменные смарти

{$smarty.server.SERVER_NAME}
{$smarty.template} текущий шаблон
{$smarty.server.SCRIPT_NAME} путь до скрипта (относительно server_root)
{$smarty.get.page} — REQUEST_URI

То есть из smarty мы можем обратиться к массиву $_SERVER и $_GET.
Например, определим, находимся ли мы сейчас на главной странице

{if $smarty.server.REQUEST_URI == «/»}кажется это главная{/if}

Отладка в smarty

Значение переменной

{$foo|@debug_print_var}

Консоль отладки, показывает все переданные данные скриптом в smarty

{debug}

Объекты (классы) в smarty

// создаем объект класса MyObject
class MyObject {
function dummy($params, &$smarty) {
return ‘method!’;
}
}
$myobj = new MyObject;

// регистрируем объект по ссылке
$smarty->register_object(‘foobar’,$myobj);
// ограничиваем доступ к методам
$smarty->register_object(‘foobar’,$myobj,array(‘meth1′,’meth2′,’prop1’));
// или так, если без ограничений
$smarty->register_object(‘foobar’,$myobj,null,false);
// Используем by_ref для объектов
$smarty->assign_by_ref(‘myobj’, $myobj);
$smarty->display(‘index.tpl’);
?>

{* доступ к методу, передача параметра *}
{foobar->meth1 p1=’foo’ p2=$bar}

{* можем поймать вывод метода *}
{foobar->meth1 p1=’foo’ p2=$bar assign=’output’}
Метод вернул {$output}

{* доступ к объекту, назначенному через assign *}
{$myobj->meth1(‘foo’,$bar)}

Posted in PHP

Leave a Reply

Ваш адрес email не будет опубликован. Обязательные поля помечены *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>