NanoMVC does not require a template engine, but you may prefer to use one for more advanced presentation logic. In this example, we'll integrate Smarty as a view layer.
Make sure Smarty is installed and working correctly. In this example, the directory structure is as follows:
/var/smarty/
/libs/
Smarty.class.php
...
/templates/
/templates_c/
/configs/
/cache/
Create a controller using Smarty directly:
/myapp/controllers/hello.php
class Hello_Controller extends NanoMVC_Controller {
public $smarty;
function index() {
// Allow NanoMVC and Smarty to cooperate with autoloaders
define('SMARTY_SPL_AUTOLOAD', 1);
// Load Smarty manually
require('/var/smarty/libs/Smarty.class.php');
// Load as a plugin
$this->load->library('Smarty', 'smarty');
// Configure Smarty
$this->smarty->setTemplateDir('/var/smarty/templates/');
$this->smarty->setCompileDir('/var/smarty/templates_c/');
$this->smarty->setConfigDir('/var/smarty/configs/');
$this->smarty->setCacheDir('/var/smarty/cache/');
// Use Smarty for rendering
$this->smarty->assign('foo', 'bar');
$this->smarty->display('hello_view.tpl');
}
}
Note: If a class with the same name already exists, NanoMVC will not attempt to load a plugin for it.
Instead of repeating setup code in every controller, it’s cleaner to create a wrapper plugin around Smarty:
/myapp/plugins/nanomvc_library_smarty_wrapper.php
define('SMARTY_SPL_AUTOLOAD', 1);
require('/var/smarty/libs/Smarty.class.php');
class NanoMVC_Library_Smarty_Wrapper extends Smarty {
function __construct() {
parent::__construct();
$this->setTemplateDir('/var/smarty/templates/');
$this->setCompileDir('/var/smarty/templates_c/');
$this->setConfigDir('/var/smarty/configs/');
$this->setCacheDir('/var/smarty/cache/');
}
}
Then update your controller to use the wrapper:
/myapp/controllers/hello.php
class Hello_Controller extends NanoMVC_Controller {
function index() {
$this->load->library('Smarty_Wrapper', 'smarty');
$this->smarty->assign('foo', 'bar');
$this->smarty->display('hello_view.tpl');
}
}
You can autoload your Smarty_Wrapper by adding it to the autoload configuration file:
/myapp/configs/config_autoload.php
$config['libraries'] = ['Smarty_Wrapper'];
This allows you to access Smarty in any controller without having to load it manually. See the Autoloading documentation for more details.