我在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函数完成,但是我该如何修改查询?
感谢所有帮助!
答案 0 :(得分:7)
答案 1 :(得分:4)
Twig有一个截断过滤器,但您必须通过在config.yml文件中添加以下内容来启用文本扩展名。
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
然后在你的模板中你可以使用截断过滤器并传递一个整数,表示截断的长度。
{{ d.modelinfo|truncate(50) }}