0
我想用php scanDir獲取所有目錄作爲數組,然後在模板中使用樹枝「for循環」。加載一個目錄用小樹枝
,這裏是我的index.php
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',
));
$dir = "movies";
$exclude = array(".","..",".*",".php");
$movies = array_diff(scandir($dir), $exclude);
echo ''; print_r($movies);
$template = $twig->loadTemplate('base.html.twig');
echo $template->render($movies);
,這裏是我的樹枝模板 - base.html.twig
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Movies</title>
</head>
<body>
<h1>Movies</h1>
<ul>
{% for movie in movies %}
<li>{{ movie }}</li>
{% endfor %}
</ul>
</body>
</html>
這裏是從我的瀏覽器輸出的源代碼
Array
(
[2] => A Movie From Twentytwelve (2012)
[3] => A Movie From Twentyfourteen (2014)
[4] => Another Movie From Twentyfourteen (2014)
[5] => index.php
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Movies</title>
</head>
<body>
<h1>Movies</h1>
<ul>
</ul>
</body>
</html>
您可以看到scandir正在獲取數組(但不排除.php文件)。你也可以看到模板正在加載,但我認爲我需要對數組做更多的事情,並在模板中正確設置變量。任何幫助表示讚賞。
謝謝你nininho!我現在使用 echo $ template-> render(['movies'=> $ movies]); – dreadycarpenter