我一直在 localhost 上测试 Twig ...这里的代码与这个问题相同,但查询不同:
<?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 的新手,并且使用他们网站上的最新版本,这很重要。