我一直在本地主机上测试Twig ...这里的代码与this question中的代码相同,但查询不同:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} catch (PDOException $e) {
echo "Error: Could not connect. " . $e->getMessage();
}
// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// attempt some queries
try {
// execute SELECT query
// store each row as an object
$sql = "SELECT manufacturer, model, modelinfo FROM automobiles WHERE id = '4' ";
$sth = $dbh->query($sql);
while ($row = $sth->fetchObject()) {
$data[] = $row;
}
// close connection, clean up
unset($dbh);
// define template directory location
$loader = new Twig_Loader_Filesystem('templates');
// initialize Twig environment
$twig = new Twig_Environment($loader);
// load template
$template = $twig->loadTemplate('cars.html');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>我有3条记录;我决定查询一个不存在的记录,看看Twig的错误处理是什么样的,因为我正在比较Twig和Smarty -出于兴趣,并且是为了一个项目。出现以下错误消息:
Notice: Undefined variable: data in /Applications/MAMP/htdocs/mysite/twigtesting.php on line 42肯定会出现“找不到数据”的通知,还是我说错了?未定义的变量数据指的是:
// set template variables
// render template
echo $template->render(array (
'data' => $data
));为什么会发生这种情况?我是Twig的新手,正在使用他们网站的最新版本,如果相关的话。
发布于 2013-02-27 06:57:31
您不会得到Twig错误,因为错误不存在于模板中,而存在于生成这些模板的代码中。
PHP在将$data的值放入数组中时遇到了问题,因为该变量不存在。
如果你想看看twig是如何处理错误的,你需要访问一个模板中不存在的变量。例如,将{{ notExisting }}放入当前模板中。
我已经可以说Twig是通过在PHP中抛出解析异常来处理错误的。Twig抛出的所有异常都在扩展Twig_Error。要捕获它们,请使用try { ... } catch (\Twig_Error $e) { ... }块。
此外,Twig可以抛出3种不同类型的异常:
当解析模板时出现错误时,会抛出
Twig_Error_Syntax (例如,当Twig无法加载文件时,会抛出格式错误的tags).Twig_Error_Loader。在使用render()方法或使用Twig中的某些文件功能时,可能会发生这种情况(例如,在运行时发生错误时抛出{% extends ... %}).Twig_Error_RunTime (例如,extensions).内部的错误
https://stackoverflow.com/questions/15100863
复制相似问题