Adding A Template Engine - ZingPHP/Zing GitHub Wiki
Zing supports different template engines, and it currently comes with Smarty and Twig as they are two very popular templating engines.
To add your own engine, you first need to create a directory in Zing/src/Modules/TemplateEngines
. The directory should be named based on the name of the engine (No Spaces) for example Smarty
or Twig
or MyAwesomeEngine
.
Next you need to copy the proper files/folders into the newly created directory. After that you will need to create a file in that directory called ZingTemplateLoader.php
and in that file you will place this:
<?php
namespace Modules\TemplateEngines\__REPLACE_ME__;
use Interfaces\ZingTemplate;
class ZingTemplateLoader implements ZingTemplate{
public function init(){
}
public function render($filename){
}
public function assign($key, $value = ""){
}
}
find __REPLACE_ME__
and replace it with the name of the directory you created from above(Smarty
, Twig
, etc.).
Finally we have to tell Zing how the framework works, which is what each function above is for.
init()
Initializes the template engine for usage.render()
Tell Zing how to render the output.assign()
Assigns values to the template engine to get rendered out.
Though it is not required that a template engine is set in your config, it is recommended. Here is how it would be set in the config file:
$config = array(
"websites" => array(
array(
"tplEngine" => "Twig",
),
)
);
Here is how Smarty's Template loader is written:
namespace Modules\TemplateEngines\Smarty;
use Interfaces\ZingTemplate;
use Smarty;
class ZingTemplateLoader implements ZingTemplate{
protected $smarty = null;
public function init(){
require_once __DIR__ . "/Smarty.class.php";
$this->smarty = new Smarty();
return $this->smarty;
}
public function render($filename){
$this->smarty->display($filename);
}
public function assign($key, $value = ""){
$this->smarty->assign($key, $value);
}
}
Twig's Template Loader is written a little bit differently because it works differently than Smarty, so its loader looks like this:
namespace Modules\TemplateEngines\Twig;
use Interfaces\ZingTemplate;
use Twig_Autoloader;
use Twig_Environment;
use Twig_Loader_Filesystem;
class ZingTemplateLoader implements ZingTemplate{
protected $twig = null;
protected $vars = array();
public function init(){
require_once __DIR__ . "/Autoloader.php";
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(__DIR__ . "/../../../../../Websites/Templates");
$this->twig = new Twig_Environment($loader);
return $this->twig;
}
public function render($filename){
$pos = strrpos($filename, "Templates/");
$filename = substr($filename, $pos + strlen("Templates/"));
$template = $this->twig->loadTemplate($filename);
echo $template->render($this->vars);
}
public function assign($key, $value = ""){
$this->vars[$key] = $value;
}
}