Documentation:Templates
From TinyMVC
Integrating a Template Engine
Although a template engine is not necessary, you may wish to integrate a template engine you like to use. In the following example, we'll demonstrate how to integrate Smarty as the view layer. We do this by loading the Smarty class as a library.
Learning by example
First, we'll show the quick and dirty method, with everything in the controller.
Make sure you have Smarty installed and setup properly. For our Example, we put it here:
/var/smarty/
/libs/
Smarty.class.php
...
/templates_c/
/configs/
/cache/
We did not setup a Smarty template directory because we want to use our existing /myapp/views/ directory for Smarty templates.
myapp/controllers/hello.php
class Hello_Controller extends TinyMVC_Controller { function index() { // require the Smarty class require('/var/smarty/libs/Smarty.class.php'); // instantiate the library $this->load->library('Smarty','smarty'); // configure Smarty $this->smarty->compile_dir = '/var/smarty/templates_c/'; $this->smarty->config_dir = '/var/smarty/configs/'; $this->smarty->cache_dir = '/var/smarty/cache/'; // we will use our view directory for template files $this->smarty->template_dir = TMVC_MYAPPDIR . 'views/'; // now just use smarty for the view layer $this->smarty->assign('foo','bar'); $this->smarty->display('hello_view.tpl'); } }
If a library classname already exists, TinyMVC will not try to load a plugin file for it.
Now this is a lot of code in the controller, and you will probably want to use Smarty elsewhere. So the more flexible solution is to create a library wrapper:
myapp/plugins/library.Smarty_Wrapper.php
// require the Smarty class require('/var/smarty/libs/Smarty.class.php'); class Smarty_Wrapper Extends Smarty { function __construct() { parent::Smarty(); $this->compile_dir = '/var/smarty/templates_c/'; $this->config_dir = '/var/smarty/configs/'; $this->cache_dir = '/var/smarty/cache/'; // we will use our view directory for template files $this->template_dir = TMVC_MYAPPDIR . 'views/'; } }
myapp/controllers/hello.php
class Hello_Controller extends TinyMVC_Controller { function index() { $this->load->library('Smarty_Wrapper','smarty'); // now just use smarty for the view layer $this->smarty->assign('foo','bar'); $this->smarty->display('hello_view.tpl'); } }
Now you can load and use Smarty with one line of code in your controller. Optionally, you can autoload the Smarty_Wrapper library in the /myapp/configs/autoload.conf file.
