Zend Framework & Smarty with Zend view helpers

If you wish to use Smarty templating engine together with Zend Framework, the following will give you an idea how it can be accomplished.

1. Download Smarty class that extends Zend_View_Abstract

Download Smarty class

Zend Framework is located in its default location: project/library/Zend
Smarty should be located in project/library/Smarty

2. Define smarty and view variables in your application config:

smarty.compile_dir = APPLICATION_PATH "/storage/smarty/compiled"
smarty.cache_dir = APPLICATION_PATH "/storage/smarty/cache"
smarty.template_dir = APPLICATION "views/templates/"
smarty.config_dir = APPLICATION "views/config/"
smarty.layout_dir = APPLICATION "views/layouts/"
app.encoding = "ISO-8859-1"

3. Initialise the view in your bootstrap class, e.g. _initView() method:

protected function _initView() {

/* Create view object, assign paths and disable checking of templates if in production */
$view = new Jazz_View_Smarty($this->_appConfig->smarty->template_dir, array(
  'cache_dir' => $this->_appConfig->smarty->cache_dir,
  'compile_dir' => $this->_appConfig->smarty->compile_dir,
  'config_dir' => $this->_appConfig->smarty->config_dir,
  'compile_check' => APPLICATION_ENV == 'production' ? FALSE : TRUE
));

/* Set correct encoding - omitting may cause problems with forms etc. */
$view->setEncoding($this->_appConfig->app->encoding);

/*
  Zend view helpers will become available as $zendView-> in smarty templates
  Examples: {$zendView->headLink()} {$zendView->headScript()}
*/
$view->assign('zendView', $view);

/* Notify the view helper */
Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')
  ->setView($view)
  ->setViewScriptPathSpec(':controller/:action.:suffix')
  ->setViewScriptPathNoControllerSpec(':action.:suffix')
  ->setViewSuffix(Jazz_View_Smarty::TEMPLATE_EXTENSION);

}

If you use Zend_Layout, you can pass the view into it:

Zend_Layout::startMvc(array(
    'layout' => 'default_layout_template_name',
    'view' => $view,
    'viewSuffix' => Jazz_View_Smarty::TEMPLATE_EXTENSION)
  )
  ->setInflectorTarget('layouts_path/:script.:suffix');

4. Use the view in your controller as usual:

public function indexAction() {
  $this->view->someVariable = array('one', 'two', 'three');
}

This becomes

{$someVariable}

in Smarty templates


SetPageWidth