Fidel Castro Fidel Castro - 1 month ago 8
Twig Question

render template that is in the views directory but inside another directory

I'm having a hard time trying to make this little modification...

I want to render a file (login.twig) which is inside my views file but in another folder: /views/ajax_files/login.twig

do I have to do this everytime ?

require 'vendor/autoload.php';


$loader = new Twig_Loader_Filesystem('views/ajax_files');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',
'auto_reload' => true,

));


echo $twig->render('login.twig');


Because on my index.php, that is already being declared
which I'm trying to write DRY code

require 'vendor/autoload.php';


$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',
'auto_reload' => true,

));


echo $twig->render('index.twig');

Answer

You can also define multiple template directories directly in your index.php with

$loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));

Please also have a look at http://twig.sensiolabs.org/doc/api.html#loaders, you could also use a loader chain or simply add the additional path to your existent filesystem loader, with some code like

$loader = $twig->getLoader();
$loader->addPath('another/path/to/templates'); //or $loader->prependPath('...')
$twig->setLoader($loader);