genshi
前項ではcheetahを紹介しましたが、本項ではgenshiを紹介します。 同じくPythonの数あるテンプレートエンジンの一つとなります。
XMTLをベースとしていますので構文エラーに対してはかなり厳しめです。 下記リンクよりダウンロードし、インストールを行いましょう。
まずはfor文から見てみましょう。 テンプレートファイルの呼び出し元のコードを記述します。
# -*- coding: utf-8 -*-
from genshi.template import TemplateLoader
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
tplLoader = TemplateLoader(['c:/python'])
tpl = tplLoader.load('genshi_for.html')
data = []
data.append(('1', 'genshi', 'template'))
data.append(('2', 'python-izm', 'com'))
data.append(('3', 'genshi', 'sample'))
return tpl.generate(data=data).render('html')
9行目でテンプレートファイルを配置しているディレクトリを指定し、続く10行目でテンプレートファイルそのものを引数で渡します。 12行目から15行目でテンプレートファイル内で参照する値を追加しています。 最後の17行目でテンプレートへ引き渡す情報を格納してレンダリングを行います。
次はテンプレートファイルの記述です。
-- ファイル名:genshi_for.html --
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
lang="ja">
<head>
<title>
Genshiテスト
</title>
</head>
<body>
<table border='1'>
<py:for each="tr in data">
<tr>
<py:for each="td in tr">
<td width='100' align='center'>
${td}
</td>
</py:for>
</tr>
</py:for>
</table>
</body>
</html>
Pythonのコードと違い閉じタグが必要となるので気を付けましょう。
-- 実行結果 --
| 1 | genshi | template |
| 2 | python-izm | com |
| 3 | genshi | sample |
次はif文です。 先程のコードのテンプレートファイルの設定を変更します。
# -*- coding: utf-8 -*-
from Cheetah.Template import Template
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
tpl = Template(file='c:/python/genshi_if.tpl')
tpl.data = []
tpl.data.append(('1', 'cheetah', 'template'))
tpl.data.append(('2', 'python-izm', 'com'))
tpl.data.append(('3', 'cheetah', 'sample'))
return tpl.respond().encode('utf-8')
テンプレートファイルは下記の通りです。
-- ファイル名:genshi_if.html --
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
lang="ja">
<head>
<title>
Genshiテスト
</title>
</head>
<body>
<table border='1'>
<py:for each="tr in data">
<py:if test="tr[1] == 'genshi'">
<tr>
<py:for each="td in tr">
<td width='100' align='center'>
${td}
</td>
</py:for>
</tr>
</py:if>
</py:for>
</table>
</body>
</html>
2列目が「genshi」のもののみ出力する形です。 for文と同じように閉じタグをきちんとつけましょう。
-- 実行結果 --
| 1 | genshi | template |
| 3 | genshi | sample |
