このサイトのように、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);
ただし、テキストを切り捨てて、拡張機能ディレクトリに追加してテキスト拡張機能をインストールしようとしましたが、機能させる方法がわからないため、次のことができます。
{{d.info|truncate(40)}}
等
私はGoogleを調べましたが、私が見つけたのはSymfonyに関連するものであり、テンプレートエンジンとしての感触を得るためにTwigを使用しています。
Twigでテキストの切り捨てを有効にするにはどうすればよいですか?