简体   繁体   中英

How to display contents of array in twig

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM