Reputation: 317
I've spent the last 3 days looking for a solution to this :/
I have a function that loops through contents of a directory:
I was putting something together but it had a ton of for loops, so I searched online and found something similar that I was able to modify to fit what I needed:
require_once "library/Twig/Autoloader.php";
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('views/');
$twig = new Twig_Environment($loader);
$dir = dirname(dirname(__FILE__)) . '/';
function fileList($dir){
global $files;
$files = scandir($dir);
foreach($files as $file){
if($file != '.' && $file != '..'){
if(is_dir($dir . $file)){
fileList($dir . $file);
}
}
}
};
fileList($dir);
Then I have this:
echo $twig->render('home.twig', array('file' => $files, 'dir' => $dir));
and in my home.twig file I have this:
<ol>
{% for key, files in file %}
<li>{{file[key]}}</li>
{% endfor %}
</ol>
What I'm trying to do is display the contents on $files using twig on the page, but I cannot wrap my head around it. pls help?
It's weird, I noticed that when I add global $files;
inside the function it outputs only the contents of the first directory and stops. can't figure out why it stops.
Upvotes: 3
Views: 10715
Reputation: 3813
Here's a slightly reworked version of the function that will recurse into subfolders and list everything in a single, flat array:
function fileList($dir, &$files = array()){
$this_dir = scandir($dir);
foreach($this_dir as $file){
if($file != '.' && $file != '..'){
if(is_dir($dir . $file)){
fileList($dir.$file.'/', $files);
} else {
$files[] = $dir . $file;
}
}
}
}
Here's a short example of function usage:
$dir = dirname(dirname(__FILE__)) . '/';
fileList($dir, $files);
echo '<h2>Scanning Directory: '.$dir.'</h2>'; //These two lines are
echo '<pre>'.print_r($files, true).'</pre>'; //just to see the results
Then in the twig output you'll only need a simple loop to display it.
<ol>
{% for key, files in file %}
<li>{{file[key]}}</li>
{% endfor %}
</ol>
Upvotes: 2