私は Twig テンプレート言語を使用して、テンプレート駆動型の小さなサイトを開発しています。
すべてが基本的にうまく機能します - http://devzone.zend.com/article/13633-Creating-Web-Page-Templates-with-PHP-and-Tw ig-part-1- の指示に従いました
ただし、2 つの点で問題があります。1 つ目は、.tpl (テンプレート) ファイルをスクリプトのテンプレート ディレクトリの外に置きたいことです。2 つ目は、PHPMyadmin 内で通貨をフォーマットするにはどうすればよいですか?
これは私のスクリプトです:
車.tpl:
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
tr.heading {
font-weight: bolder;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<h2>Countries and capitals</h2>
<table>
<tr class="heading">
<td>Manufacturer</td>
<td>Specification</td>
<td>Price</td>
</tr>
{% for d in data %}
<tr>
<td>{{ d.car|escape }}</td>
<td>{{ d.spec|escape }}</td>
<td>{{ d.price|escape }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
これは PHP Twig スクリプトです。
<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();
// attempt a connection
try {
$dbh = new PDO('mysql:dbname=whatcar1;host=localhost', 'root', 'PASSWORD');
} 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 vehicles";
$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.tpl');
// set template variables
// render template
echo $template->render(array (
'data' => $data
));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
データベースは、次のフィールドを使用して次の方法で保存されます。
car VARCHAR 255
spec VARCHAR 255
price VARCHAR 255
SQL クエリですべてのフィールドが選択されているにもかかわらず、フィールドの価格が表示されません。
どこが間違っていますか? このエラーを修正するにはどうすればよいですか? また、テンプレート ディレクトリの外に .tpl ファイルを保存していますが、これを実行中のスクリプトにどのように統合すればよいでしょうか。
それ以外の場合は、すべてうまくいっています。このテンプレートは、私の小規模なサイトに役立つはずです!