Zend и Smarty

Чтобы использовать шаблонизатор Smarty в Zend Framework‘е можно или расширить базовый класс Zend_View_Abstract или же создать новый, реализующий интерфейс Zend_View_Interface.
Ниже привожу куски кода первого варианта:

  1. class SmartyView extends Zend_View_Abstract
  2. {
  3.     protected $_smarty;
  4.     public function __construct($config = array())
  5.     {
  6.         $this->_smarty = new Smarty();
  7.         if(!isset($config[‘templateDir’]))
  8.             throw new Exception(‘templateDir is not set for’ . get_class($this));
  9.         else
  10.             $this->_smarty->template_dir = $config[‘templateDir’];
  11.         if(!isset($config[‘compileDir’]))
  12.             throw new Exception(‘compileDir is not set for ‘.get_class($this));
  13.         else
  14.             $this->_smarty->compile_dir = $config[‘compileDir’];
  15.         if(isset($config[‘configDir’]))
  16.             $this->_smarty->config_dir = $config[‘configDir’];
  17.  
  18.         if(isset($config[‘pluginDir’]))
  19.             $this->_smarty->plugin_dir[] = $config[‘pluginDir’];
  20.  
  21.         parent::__construct($config);
  22.     }
  23.     public function getEngine()
  24.     {
  25.         return $this->_smarty;
  26.     }
  27.     public function __set($key,$val)
  28.     {
  29.         $this->_smarty->assign($key,$val);
  30.     }
  31.     public function __isset($key)
  32.     {
  33.         $var = $this->_smarty->get_template_vars($key);
  34.         if($var)
  35.             return true;
  36.         return false;
  37.     }
  38.     public function __unset($key)
  39.     {
  40.         $this->_smarty->clear_assign($key);
  41.     }
  42.     public function assign($spec,$value = null)
  43.     {
  44.         if($value === null)
  45.             $this->_smarty->assign($spec);
  46.         else
  47.             $this->_smarty->assign($spec,$value);
  48.     }
  49.     public function clearVars()
  50.     {
  51.         $this->_smarty->clear_all_assign();
  52.     }
  53.     public function display($file)
  54.     {
  55.         $this->_smarty->display($file . ‘.tpl’);
  56.     }
  57.     protected function _run()
  58.     {
  59.         $this->strictVars(true);
  60.         $this->_smarty->assign_by_ref(‘this’,$this);
  61.         $templateDirs = $this->getScriptPaths();
  62.         $file = substr(func_get_arg(0),strlen($templateDirs[0]));
  63.         $this->_smarty->template_dir = $templateDirs[0];
  64.         $this->_smarty->compile_id = $templateDirs[0];
  65.         echo $this->_smarty->fetch($file);
  66.     }
  67. }

Далее в index.php или где мы там запускаем наше приложение, подключаем смарти и заносим его в реестр

  1. Zend_Loader::loadClass(‘Zend_View_Abstract’);
  2. include(‘Smarty/Smarty.class.php’);
  3. include(‘ZendViewSmarty.php’);
  4. $arrConfigSmarty = array(‘templateDir’ => ‘./application/views/scripts/’,
  5.                         ‘compileDir’ => ‘./cache/template_c’ );
  6. $smarty = new SmartyView($arrConfigSmarty);
  7. $registry->set(’smarty’, $smarty);
  8. /* … */
  9. $frontController->setParam(‘noViewRenderer’, true);

Конфигурация смарти в данном примере хардкодирована, её обычно поднимают откудато, дальше контроллер

  1. class IndexController extends Zend_Controller_Action
  2. {
  3.     public function init()
  4.     {
  5.         $this->view = Zend_Registry::get(’smarty’);
  6.     }
  7.     public function indexAction()
  8.     {
  9.         $this->view->assign(‘title’, ‘заголовок’);
  10.         $this->view->display(‘index/index’);
  11.     }
  12. }
google.com bobrdobr.ru del.icio.us technorati.com linkstore.ru news2.ru rumarkz.ru memori.ru moemesto.ru

Похожие записи:

  • Аналог функции file_get_contents() для загрузки данных с посторонних ресурсов (используем библиотеку curl)
  • Функция генерации кода/ключа активации для подтверждения регистрации на сайте
  • PCRE: Краткое описание синтаксиса
  • Для новоиспеченных PHP’шников:
  • Новые возможности PHP 5.3
  • Метки:

    2 отзывов на “Zend и Smarty”

    1. axl сказал:

      коешо по этой теме:

      Writing a CMS/Community with Smarty and the Zend Framework
      http://www.prodevtips.com/2007/11/02/writing-a-cms-with-smarty-and-the-zend-framework-part-1/

    2. Zver сказал:

      есть index.php, IndexController.php and index.tpl все сделал как вы описали в index.php, и IndexController.php в index.tpl папу символов для наглядности набрал…
      $this->view->display(‘index/index’);
      это не выводит мне мой код из index.tpl хотя в переменной title хранятся данные - ЭзаголовокЭююю тоесть все приинклудилось и отработалло… что дальше писать в index.php для вывода всего этого на экран?

    Оставить ответ