我正在尝试使用php scanDir将所有目录作为数组获取,然后在模板中使用twig“for loop”。
这是我的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);
这是我的twig模板 - 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文件)。你也可以看到模板正在加载,但我想我需要对数组做更多的事情,并在模板中正确设置变量。任何帮助表示赞赏。
答案 0 :(得分:1)
是。 array_diff可以根据需要比较完整条目,但不能与文件掩码一起使用。请查看pathinfo()以检索文件的扩展名,并通过array_filter()过滤它们。
第二件事是,你必须将$movies
包装在一个数组中。尝试
$template->render(['movies' => $movies]).
否则,您将在模板文件中使用数字变量键(2,3,4,5)。