使用Twig遍历文件

时间:2019-02-26 13:52:03

标签: php twig

我有一个用PHP编写的for循环,该循环对于文件夹“ patterns”中的每个.html文件,它将获取html信息并进行呈现,并将html内容放置在页面上以供参考。 php代码取自于以下位置的Styleguide Generator:

https://github.com/adactio/Pattern-Primer/blob/master/index.php

如何将下面的代码转换为Twig模板引擎可以使用的代码?

<?php
$files = array();
$handle=opendir('patterns');
while (false !== ($file = readdir($handle))):
    if(substr($file, -5) == '.html'):
        $files[] = $file;
    endif;
endwhile;
sort($files);
foreach ($files as $file):
    echo '<div class="pattern">';
    echo '<div class="display">';
    include('patterns/'.$file);
    echo '</div>';
    echo '<div class="source">';
    echo '<textarea rows="6" cols="30">';
    echo htmlspecialchars(file_get_contents('patterns/'.$file));
    echo '</textarea>';
    echo '<p><a href="patterns/'.$file.'">'.$file.'</a></p>';
    echo '</div>';
    echo '</div>';
endforeach;
?>

2 个答案:

答案 0 :(得分:1)

以下内容仅在使用FilesystemLoader时有效-代码是为twig 2.x编写的,未经测试


twig注册Filesystemloader

<?php
    require_once '/path/to/vendor/autoload.php';

    $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
    $twig = new \Twig\Environment($loader);

    $twig->addFunction(new \Twig\TwigFunction('get_folder', function (\Twig\Environment $twig, $folder) {
            foreach($twig->getLoader()->getPaths() as $view_path) {
                if (is_dir($view_path.'/'.$folder)) {
                    $location = $view_path.'/'.$folder;
                    break;
                }
            }
            if ($location === null) return [];
            $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($location, \RecursiveDirectoryIterator::SKIP_DOTS),\RecursiveIteratorIterator::SELF_FIRST);

            $templates = [];
            foreach($it as $path) $templates[] = str_replace($view_path.'/', '', $path);
            return $templates;
    }, ['needs_environment' => true, ]);

twig

中使用新功能
{% for template in get_folder('patterns') %}
    {% include template %}
{% endfor %}

答案 1 :(得分:-1)

我认为您正在寻找的是交响枝入门/教程: https://symfony.com/doc/current/templating.html