如何配置 Twig 来查找模板?

How to configure Twig to find templates?

我将 Twig 与 Slim 一起使用,但出现以下错误:

Warning: file_get_contents(application/templates/config.html): failed to open stream: No such file or directory in /var/www/testing/vendor/twig/twig/lib/Twig/Loader/Filesystem.php on line 131

下面的脚本位于 /var/www/testing/html/index.php,我已验证该模板存在于 /var/www/testing/application/templates/config.html

$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('../application/templates', [
        //'cache' => 'path/to/cache'    // See auto_reload option
        'debug' => true,
        'strict_variables'=> true
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $c['router'],
        $c['request']->getUri()
    ));
    $view->addExtension(new \Twig_Extension_Debug());
    return $view;
};

$app->get('/config', function (Request $request, Response $response) {
    return $this->view->render($response, 'config.html',[]);
});

第 131 行如下所示 returns config.html.

public function getSource($name)
{
    return file_get_contents($this->findTemplate($name));
}

我在另一个类似的服务器上使用过相同的脚本(但是,PHP 版本可能不同,php.ini 和 httpd.conf 可能不同),没有这个问题吗?

显然,我配置不正确。我应该如何配置 Twig 来查找模板?

是的,这是我上周遇到的问题(错误?),@geggleto 解决了它。

这是因为 Twig 从 1.24.2 更新了 v1.26.1

Twig在1.24.2中是这样抓取的(方法Twig_Loader_Filesystem::normalizeName):

protected function normalizeName($name)
{
    return preg_replace('#/{2,}#', '/', str_replace('\', '/', (string) $name));
}

这就是它在 1.26.1 中抓取文件的方式:

private function normalizePath($path)
{
    $parts = explode('/', str_replace('\', '/', $path));
    $isPhar = strpos($path, 'phar://') === 0;
    $new = array();
    foreach ($parts as $i => $part) {
        if ('..' === $part) {
            array_pop($new);
        } elseif ('.' !== $part && ('' !== $part || 0 === $i || $isPhar && $i < 3)) {
            $new[] = $part;
        }
    }
    return implode('/', $new);
}

看到 array_pop($new); 行了吗?那是破坏相对路径使用的那个。

@geggleto 建议使用绝对路径而不是相对路径,它奏效了:

\Slim\Views\Twig(__DIR__.'/../application/templates')

总结一下:这是因为 Twig 的新版本。