Recursive twig template file search in Subdirectories of template folder

631 Views Asked by At

I've made my own library of components (twig files) for timber. It's a problem to include paths in twig templates, because my library has tree structure and grows I want the way to include like that {% include "map-header" %} any file from the file tree and I vahe some trees, it should be possible to give a priority.

Now I use php function to search twig files in subtirectories and include them like that {% include fn('block','map-header') %}

My current php function:

function block($name){

$locations = array(
FRONTPATH.'app/blocks/site.blocks/',
FRONTPATH.'app/blocks/common.blocks/',
FRONTPATH.'app/blocks/ok.blocks/',
FRONTPATH.'app/blocks/base.blocks/'
);

foreach ($locations as $location) {
    $path = realpath($location);

    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
    {
        $filename = str_replace(DIRECTORY_SEPARATOR,"/",$filename);

        if(preg_match('/\/'.$name.'.twig/',$filename)){

           return explode('/frontend/', $filename)[1];
        }
    }

}

return; }

1

There are 1 best solutions below

0
On

Thats my solution

$root= FRONTPATH.'app/blocks/';
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);

$paths = array($root);
foreach ($iter as $path => $dir) {
 if ($dir->isDir() && strpos( $path, '.git' ) == false) {
    $paths[] = $path;
 }
}

Timber::$locations = $paths;