Today I came up with a better
solution that lets you take advantage
of Twig full features without any hack
(like the partial tag I was
talking about in my previous post).
Instead of parsing the generated output
as a string with Twig, we can store it
into a template, which lets us use
features like use, extends, include,
thing that is almost impossible – in a clean way –
if we use the Twig string loader:
123456789101112131415161718
<?phpclassFramework_Base_Controller{publicfunctionrender($templateName,array$parameters=array()){// ....// do stuff to render your template// we have the HTML output in the $templateOutput variable// ...$twig=newTwig_Environment(newTwig_Loader_String(),array('autoescape'=>false,));return$twig->render($templateOutput,$parameters);}}
Instead of using the Twig_String_Loader we would use an array
loader, and store $templateOutput in a unique template, called __MAIN__.
<?phpclassFramework_Base_Controller{publicfunctionrender($templateName,array$parameters=array()){// ....// do stuff to render your template// we have the HTML output in the $templateOutput variable// ...$finder=newSymfony\Component\Finder\Finder();$templates=array();foreach($finder->in('/path/to/twig/templates')as$file){if(!$file->isDir()){$templates[$file->getRelativePathName()]=$file->getContents();}}$loader=newTwig_Loader_Array($templates);$loader->setTemplate('__MAIN__',$templateOutput);$twig=newTwig_Environment($loader,array('autoescape'=>false,));try{return$this->twig->render($templateName,array(...));}catch(Twig_Error_Loader$e){return$this->twig->render("__MAIN__",array(...));}}}