Twig模板完全无法加载,返回空白页寻求技术解决方案
Twig模板加载失败返回空白页(500内部服务器错误)排查记录
我刚接触Twig,入门阶段就碰到了棘手的问题——Twig完全加载不了任何模板,浏览器直接返回空白页,打开控制台一看是500内部服务器错误。我已经排查过拼写错误、目录路径问题,甚至开启了debug模式也没得到有效提示,折腾了好一阵才找到原因。
先说说我的环境和文件结构:
- 系统:Fedora Workstation 27
- PHP版本:7.2.5
- Twig版本:2.4.8
文件结构如下:
-app/ ---vendor/ ---cache/ ---templates/ ------- home.html ---hi.php
我的hi.php代码:
<?php require_once 'vendor/autoload.php'; class twiger { private static $twig; public static function twig() { $templatedir = __DIR__.'templates'; if ( ! isset(self::$twig)) { $loader = new Twig_Loader_Filesystem(array($templatedir)); self::$twig = new Twig_Environment($loader); } return self::$twig; } } $msg = "Hello World"; $tw = twiger::twig(); echo $tw->render("home.html", array('msg' => $msg)); ?>
home.html模板代码:
<html> <head> <title>hello</title> </head> <body> <h4>the meassage is:<h4> <H2> {{ msg }} </H2> </body> </html>
问题解决
折腾了半天后发现,问题出在缺失composer.json和composer.lock文件。把这两个文件放到app/目录下对应的位置后,Twig就能正常加载模板了。
后来想了想,应该是因为Twig是通过Composer安装的,这两个文件是Composer管理依赖的核心文件,缺失的话vendor/autoload.php可能无法正确加载Twig的类文件,从而触发了500错误。
内容的提问来源于stack exchange,提问作者Jamen
相关产品推荐
相关产品推荐

