[英]How to display contents of array in twig
過去 3 天我一直在尋找解決方案:/
我有一個循環遍歷目錄內容的函數:
我把一些東西放在一起,但它有很多 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);
然后我有這個:
echo $twig->render('home.twig', array('file' => $files, 'dir' => $dir));
在我的 home.twig 文件中,我有這個:
<ol>
{% for key, files in file %}
<li>{{file[key]}}</li>
{% endfor %}
</ol>
我想要做的是在頁面上使用 twig 顯示 $files 上的內容,但我無法繞過它。 請幫忙?
很奇怪,我注意到當我添加global $files;
在函數內部,它只輸出第一個目錄的內容並停止。 無法弄清楚為什么它會停止。
這是該函數的一個稍微重新設計的版本,它將遞歸到子文件夾中並在單個平面數組中列出所有內容:
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;
}
}
}
}
下面是函數使用的一個簡短示例:
$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
然后在樹枝輸出中,您只需要一個簡單的循環來顯示它。
<ol>
{% for key, files in file %}
<li>{{file[key]}}</li>
{% endfor %}
</ol>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.