我将 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 行如下所示,返回 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 的新版本。
关于php - 如何配置 Twig 来查找模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40073663/