根据this site,我一直在学习如何使用Twig。 这是我的代码,是教程的变体:
的index.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);
但是,我想截断文本并尝试通过将其添加到extensions目录来安装Text扩展,但我不知道如何让它工作,所以我可以这样做:
{{d.info|truncate(40)}}
等
我确实在谷歌上看过,但我发现它与Symfony相关,我正在使用Twig,只是为了感受它作为模板引擎。
如何在Twig中启用截断文本?
答案 0 :(得分:2)
你已经有了一半的解决方案,因为看起来你只是缺少添加扩展,这与你对escaper扩展的基本相同:
$twig->addExtension(new Twig_Extensions_Extension_Text());
应该这样做。
答案 1 :(得分:1)
在config.yml中启用它的服务:
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }