Twig Loader Namespacing

php, symfony, twig

Solution

There are, it is called Twig namespaces: http://twig.sensiolabs.org/doc/api.html#built-in-loaders

$loader->addPath(dirname(__DIR__).'/src/Test/Core/Resources/views', 'core');
$loader->addPath( dirname(__DIR__). '/src/Test/User/Resources/views', 'user');

Now your paths are like `@user/partials/sidebar.html.twig`, `@core/...`, etc.

Problem

I am slowly refactoring my code, and I am using TWIG for my templating "engine" in PHP. My current directory structure in my application is as follows (PSR-4) - ``` src/ Test/ User/ Resources/ views/ Test/ Core/ Resources/ views/ ``` I am using the following code to load TWIG - ``` Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem(array( dirname(__DIR__). '/src/Test' )); $twig = new Twig_Environment($loader, array( 'cache' => dirname(__DIR__). '/app/storage/cache', 'debug' => true, )); ``` Currently, it works fine and allows me to call each TWIG file like - ``` echo $twig->render('User\Resources\views\partials\sidebar.html.twig', $data); ``` Although, typing all of that is time consuming, and I would like to simplify it. Is there anyway to do it how Symfony autoloads bundles? I have attempted to use this in my loader as well, but if there are similar directories in the views folder everything is overwritten by the first view found. For example - Core/Resources/views/partials/sidebar.twig would be used instead of User/Resources/views/partials/sidebar.twig ``` $loader = new Twig_Loader_Filesystem(array( dirname(__DIR__). '/src/Test/Core/Resources/views', dirname(__DIR__). '/src/Test/User/Resources/views', )); ``` Thoughts? Thanks!

Original source