根据这个网站,我一直在学习如何使用 Twig 。这是我的代码,是教程的变体:
索引.php:
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=articles;host=localhost', 'test', 'testing');
} 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 * FROM schedule GROUP BY airtime";
$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);
$escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);
// load template
$template = $twig->loadTemplate('countries.tmpl');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
和模板页面:
{% for d in data %}
<tr>
<td>{{ d.articleid }}</td>
<td>{{ d.articlename }}</td>
<td>{{ d.info }}</td>
</tr>
{% endfor %}
通过以下方式启用自动转义:
$twig = new Twig_Environment($loader);
$escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);
但是,我想截断文本并尝试通过将文本扩展添加到扩展目录来安装它,但我不知道如何让它工作,所以我可以这样做:
{{d.info|truncate(40)}}
等等
我确实在谷歌上看过,但我发现与 Symfony 相关,我正在使用 Twig,只是为了感受一下它作为模板引擎的感觉。
我应该怎么做才能在 Twig 中截断文本?