Smarty – один из самых известных шаблонизаторов. Шаблонизатор нужен для разделения PHP-кода от HTML-кода. Если первый раз с этим сталкиваешься, преимущества такого подхода заметны не сразу, но потом ты удивляешься, как раньше мог обходиться без шаблонов.
- Smarty довольно быстр (есть и более быстрые шаблонизаторы, но на практике узким местом в проекте является не шаблонизатор, а база данных).
- Он эффективен, так как PHP делает за него грязную работу.
- Никакой лишней обработки шаблонов, они компилируются только один раз. Перекомпилируются только те шаблоны, которые изменились.
- Можно создавать пользовательские функции и модификаторы, что делает язык шаблонов чрезвычайно расширяемым.
- Конструкции if/elseif/else/endif передаются обработчику PHP, так что синтаксис выражения {if …} может быть настолько простым или сложным, насколько вам угодно.
- Допустимо неограниченное вложение секций, условий и т. д.
- Встроенный механизм кеширования.
Рассмотрим примеры с использованием Smarty из готового проекта:
Файл index.php
<?php //error_reporting (E_ALL); @session_start(); define ( 'DS', DIRECTORY_SEPARATOR ); define ( 'DIR_ROOT', dirname(__FILE__) . DS ); define ( 'DIR_ENGINE', DIR_ROOT . 'engine' . DS ); require_once ( DIR_ENGINE . 'init.php' );
Файл engine/init.php
<?php require_once( DIR_ENGINE . 'classes/Application.php' ); Application::setDefine( 'DIR_MODULES', DIR_ENGINE . 'modules' . DS ); Application::setDefine( 'DIR_CLASSES', DIR_ENGINE . 'classes' . DS ); ..... // ==========[ Ш А Б Л О Н ]========== \\ ..... Application::setDefine( 'TEMPLATE_PATH', '/templates/' . $config['template_name'] . '/' ); Application::setDefine( 'SMARTY_TEMPLATE_PATH', DIR_ROOT . TEMPLATE_PATH ); // подключаем класс Smarty //Application::loadFile( DIR_ENGINE . 'Smarty-3.1.21/libs/Smarty.class.php',false); //$tpl = new Smarty; // Если необходимо в своих шаблонах использовать вставки на PHP то подключаем SmartyBC.class.php Application::loadFile( DIR_ENGINE . 'Smarty-3.1.21/libs/SmartyBC.class.php', false ); $tpl = new SmartyBC; $tpl->setTemplateDir( SMARTY_TEMPLATE_PATH ); $tpl->setCacheDir( SMARTY_TEMPLATE_PATH . '/cache' ); $tpl->setConfigDir( SMARTY_TEMPLATE_PATH . '/configs' ); $tpl->setCompileDir( SMARTY_TEMPLATE_PATH . '/compile' ); if ( !$config['charset'] or $config['charset'] == "" ) { $config['charset'] = "utf-8"; } $tpl->assign( 'charset', $config['charset'] ); if ( isset( $config['description'] ) and $config['description'] != "" ) { $tpl->assign( 'description', $config['description'] ); } else { $tpl->assign( 'description', "" ); } if ( isset( $config['keywords'] ) and $config['keywords'] != "" ) { $tpl->assign( 'keywords', $config['keywords'] ); } else { $tpl->assign( 'keywords', "" ); } $tpl->assign( 'cms_config', $config ); $tpl->assign( 'cms_menu', $menu ); $tpl->assign( 'Template', TEMPLATE_PATH ); $tpl->assign( 'HTTP_HOST', Application::getProtocol() . $_SERVER["HTTP_HOST"] . "/" ); $tpl->caching = false; $tpl::PHP_ALLOW; //$tpl->debugging = true; // ==========[ Ш А Б Л О Н ]========== \\ ..... Application::loadFile( DIR_CLASSES . 'Route.php', false ); $Route = new Route; $Route->start();
Файл engine/classes/Application.php
<?php class Application { ..... /************************************************************************** * Вывод страницы **************************************************************************/ public static function showPage( $tpl_file = '' ) { if ( $tpl_file != '' ) { global $DBH, $tpl; $DBH = null; $tpl->createTemplate( $tpl_file ); $tpl->display( $tpl_file ); } } public static function ShowError() { global $tpl; $e404 = $tpl->fetch( "404.tpl" ); $tpl->assign( 'Content', $e404 ); } }
Файл templates/НазваниеШаблона/index.tpl
{include file="meta.tpl"} {include file="header.tpl"} {include file="menu.tpl"} {if $cms_config.slider} {include file="slider.tpl"} {/if} {if !isset($ContentColumn)} {assign var="ContentRow" value="2"} {/if} {if $ContentColumn=1} {include file="content_1.tpl"} {elseif $ContentColumn=2} {include file="content_2.tpl"} {elseif $ContentColumn=3} {include file="content_3.tpl"} {/if} {include file="footer.tpl"}
Файл templates/НазваниеШаблона/content_2.tpl
<!-- content --> <div class="wrapper row3"> <div id="container"> <!-- ################################################################################################ --> <div class="three_quarter first"> {if !isset($Info)} {assign var="Info" value=""} {/if} {if $Info != ''} <section class="clear"><div class="alert-msg rnd8 info">{$Info}</div></section> {/if} {if !isset($ErrMsg)} {assign var="ErrMsg" value=""} {/if} {if $ErrMsg != ''} <section><div class="alert-msg rnd8 error">{$ErrMsg}</div></section> {/if} {$Content|default:' '} </div> <!-- ################################################################################################ --> <div id="sidebar_1" class="sidebar one_quarter"> <aside> <!-- ########################################################################################## --> {include file="box/login.tpl"} {include file="box/nav.tpl"} <!-- ########################################################################################## --> </aside> </div> <!-- ################################################################################################ --> <div class="clear"></div> </div> </div>
Файл engine/modules/index.php
<?php function index() { global $Route; $_SESSION['section'] = 'home'; if ( !isRouteError() ) { if ( $Route->action != '' ) { if ( function_exists( 'action_' . $Route->action ) ) { call_user_func( 'action_' . $Route->action ); } else { action_Index(); } } } else { Application::showPage( 'index.tpl' ); } } function action_Index() { global $DBH, $tpl; $q = "SELECT page_text"; $q .= " FROM 15static"; $q .= " WHERE name = 'index_info'"; $STH = $DBH->query( $q ); if ( $STH->rowCount() == 1 ) { $data = $STH->fetch( PDO::FETCH_ASSOC ); $data["page_text"] = $tpl->fetch( 'string:' . $data["page_text"] ); $tpl->assign( "Content", $data["page_text"] ); } else { Application::ShowError(); } Application::showPage( 'index.tpl' ); }
Файл engine/modules/catalog.php
<?php function index() { global $Route; $_SESSION['section'] = 'catalog'; if ( !isRouteError() ) { if ( $Route->action != '' ) { if ( function_exists( 'action_' . $Route->action ) ) { call_user_func( 'action_' . $Route->action ); } else { action_Index(); } } } else { Application::showPage( 'view/catalog/index.tpl' ); } } function action_Index() { global $DBH, $tpl; $q = "SELECT *"; $q .= " FROM 15goods_group"; $q .= " ORDER BY name ASC"; $STH = $DBH->query( $q ); if ( $STH->rowCount() > 0 ) { $data = $STH->fetchAll( PDO::FETCH_ASSOC ); $tpl->assign( "list_group", $data ); } else { $tpl->clearAssign( 'list_group' ); $tpl->assign( 'Content', 'Группы товаров пока не заполнены.' ); } Application::showPage( 'view/catalog/index.tpl' ); } function action_Showgroup() { global $DBH, $tpl, $Route; $q = "SELECT 15goods.*, 15goods_group.name AS group_name"; $q .= " FROM 15goods"; $q .= " INNER JOIN 15goods_group ON 15goods.id_group = 15goods_group.id"; $q .= " WHERE 15goods.id_group = " . $Route->idn; $q .= " ORDER BY 15goods.name ASC"; $STH = $DBH->query( $q ); if ( $STH->rowCount() > 0 ) { $data = $STH->fetchAll( PDO::FETCH_ASSOC ); $tpl->assign( "list_goods", $data ); } else { $tpl->assign( 'Content', 'Группы товаров пока не заполнены.' ); } Application::showPage( 'view/catalog/index.tpl' ); } function action_Showcard() { global $DBH, $tpl, $Route; $q = "SELECT *"; $q .= " FROM 15goods"; $q .= " WHERE id = " . $Route->idn; $STH = $DBH->query( $q ); if ( $STH->rowCount() > 0 ) { $data = $STH->fetch( PDO::FETCH_ASSOC ); $tpl->assign( "good_card", $data ); } else { Application::ShowError(); } Application::showPage( 'view/catalog/index.tpl' ); }
Файл templates/НазваниеШаблона/view/catalog/index.tpl
{include file="meta.tpl"} {include file="header.tpl"} {include file="menu.tpl"} {if $cms_config.slider} {include file="slider.tpl"} {/if} <!-- content --> <div class="wrapper row3"> <div id="container"> <!-- ################################################################################################ --> <div class="three_quarter first"> {if !isset($Info)} {assign var="Info" value=""} {/if} {if $Info != ''} <section class="clear"><div class="alert-msg rnd8 info">{$Info}</div></section> {/if} {if !isset($ErrMsg)} {assign var="ErrMsg" value=""} {/if} {if $ErrMsg != ''} <section><div class="alert-msg rnd8 error">{$ErrMsg}</div></section> {/if} {if isset($list_group)} {include file="view/catalog/list_group.tpl"} {/if} {if isset($list_goods)} {include file="view/catalog/list_goods.tpl"} {/if} {if isset($good_card)} {include file="view/catalog/good_card_so.tpl"} {/if} </div> <!-- ################################################################################################ --> <div id="sidebar_1" class="sidebar one_quarter"> <aside> <!-- ########################################################################################## --> {include file="box/login.tpl"} {include file="box/nav.tpl"} <!-- ########################################################################################## --> </aside> </div> <!-- ################################################################################################ --> <div class="clear"></div> </div> </div> {include file="footer.tpl"}
Файл templates/НазваниеШаблона/view/catalog/list_group.tpl
<table> <thead><tr><th>Перечень групп товаров</th></tr></thead> <tbody> {foreach from=$list_group item=r name=rec} {if $smarty.foreach.rec.index % 2 == 0}<tr class="light">{else}<tr class="dark">{/if} <td><a href="{insert name="url" m="catalog" a="showgroup" idn="{$r.id}"}">{$r.name}</a></td></tr> {foreachelse} [.. no results ..] {/foreach} </tbody> </table>
Файл templates/НазваниеШаблона/view/catalog/list_goods.tpl
<table> <thead><tr><th colspan="2">Перечень товаров в группе</th></tr></thead> {foreach from=$list_goods item=r name=rec} {if $smarty.foreach.rec.index % 2 == 0}<tr class="light">{else}<tr class="dark">{/if} <td><a href="{insert name="url" m="catalog" a="showcard" idn="{$r.id}"}">{$r.name}</a></td> <td width="2%">{if $r.photo != ''}<span class="icon-camera center"></span>{else} {/if}</td></tr> {foreachelse} .. no results .. {/foreach} </table>
Файл templates/НазваниеШаблона/view/catalog/good_card.tpl
<div class="pricingtable-wrapper rnd10"> <div class="pricingtable"> <div class="pricingtable-title"> <h2>{$good_card.name}</h2> </div> <div class="pricingtable-list"> <ul> {if isset($good_card.status) and {$good_card.status} != ''}<li>{$good_card.status}</li>{/if} {if isset($good_card.marka) and {$good_card.marka} != ''}<li>{$good_card.marka}</li>{/if} {if isset($good_card.model) and {$good_card.model} != ''}<li>{$good_card.model}</li>{/if} {if isset($good_card.noem) and {$good_card.noem} != ''}<li>{$good_card.noem}</li>{/if} {if isset($good_card.emgine) and {$good_card.emgine} != ''}<li>{$good_card.emgine}</li>{/if} {if isset($good_card.year) and {$good_card.year} != ''}<li>{$good_card.year}</li>{/if} {if isset($good_card.brand) and {$good_card.brand} != ''}<li>{$good_card.brand}</li>{/if} {if isset($good_card.lp) and {$good_card.lp} != ''}<li>{$good_card.lp}</li>{/if} {if isset($good_card.fr) and {$good_card.fr} != ''}<li>{$good_card.fr}</li>{/if} {if isset($good_card.ud) and {$good_card.ud} != ''}<li>{$good_card.ud}</li>{/if} {if isset($good_card.color) and {$good_card.color} != ''}<li>{$good_card.color}</li>{/if} {if isset($good_card.memo) and {$good_card.memo} != ''}<li>{$good_card.memo}</li>{/if} {if isset($good_card.price) and {$good_card.price} != ''}<li>{$good_card.price}</li>{/if} {if isset($good_card.photo) and {$good_card.photo} != ''} {php} global $tpl; $argc= $tpl->getTemplateVars('good_card'); foreach ($argc as $k => $v) { if ($k == 'photo') { $arimg = explode(", ",$v); foreach ($arimg as $ik => $iv) { echo "<li><figure class=\"center\"><a href=\"$iv\" target=\"_blank\"><img src=\"$iv\"></a></figure></li>"; } } } {/php} {/if} </ul> </div> </div> </div>