[英]How to display contents of array in twig
I've spent the last 3 days looking for a solution to this :/过去 3 天我一直在寻找解决方案:/
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:我把一些东西放在一起,但它有很多 for 循环,所以我在网上搜索并找到了类似的东西,我可以修改以适应我的需要:
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:在我的 home.twig 文件中,我有这个:
<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.我想要做的是在页面上使用 twig 显示 $files 上的内容,但我无法绕过它。 pls help?
请帮忙?
It's weird, I noticed that when I add global $files;
很奇怪,我注意到当我添加
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.