我在 MAMP 的 localhost 上创建了这个简单的 Twig 页面:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 0.5px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Automobiles</h2>
<table>
<tr class="heading">
<td>Vehicle</td>
<td>Model</td>
<td>Price</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.manufacturer|escape }}</td>
<td>{{ d.model|escape }}</td>
<td>{{ d.modelinfo|raw }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
这是它背后的代码:
<?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, price FROM automobiles";
$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());
}
?>
但是,我打算截断 modelinfo 字段中的文本,我相信这可以在 MySQL 中使用 select LEFT 函数完成,但是我应该如何修改查询?
感谢所有帮助!