djangoで、テンプレートエンジンgenshiを使う

gumiの四柳です。

tracなどで使われている、genshi ( http://genshi.edgewall.org/ ) というPythonのテンプレートエンジンがありますが、Djangoでgenshiを使ってページを出力する方法です。

virtualenvを使って仮想環境を構築し、ページを出力するまでを書きます。

環境はmac osx 10.6です。

バーチャル環境を作成する

ディレクトリの作成


$ sudo easy_install virtualenv
$ virtualenv --no-site-packages ~/.virtualenvs/testproject

mac, macports, python2.7 の場合

macで python2.7を使うのであれば、macportsを使って、


$ sudo port install python27
$ sudo port install py27-virtualenv
$ virtualenv-2.7 --no-site-packages ~/.virtualenvs/testproject
でも良いでしょう。

必要パッケージのインストール


$ workon testproject
$ pip install django
$ pip install genshi
$ pip install django-genshi

プロジェクトのワークスペースを作成

任意のディレクトリで


$ mkdir testworkspace
$ cd testworkspace
$ django-admin.py startproject testproject
$ cd testproject
$ python manage.py runserver

ブラウザで、 http://127.0.0.1:8000/ にアクセスを行い、
「It worked!」のページが表示されれば、Djangoの基本動作は出来ています。

テスト用appの追加


$ django-admin.py startapp testapp

テンプレートディレクトリの作成


$ mkdir -p templates/testapp

ディレクトリ構成

この段階でのディレクトリ構成は、以下のようになります。


testworkspace
testproject
urls.py
settings.py
testapp
views.py
templates
testapp
(これ以外にもファイルはありますが省略)

settings.pyの編集

Genshiを組み込む

settings.pyに追記します。


GENSHI_TEMPLATE_LOADERS = (
'django_genshi.loaders.app_directories.load_template',
'django_genshi.loaders.filesystem.load_template',
)

urls.py の編集

urls.py に、 testappを組み込みます。
このようになります


from django.conf.urls.defaults import *
import testapp.views

urlpatterns = patterns('',
(r'^testapp/', testapp.views.index),
)

ビューコントローラの作成

testapp/views.py を編集し、簡単なindexメソッドを書きます。このようになります。


import random
from genshi.core import Markup
from django_genshi import render_to_response

def index(request):
def b():
return random.choice( (True,False) )
l = [
Markup('<a href="example.com">example</a>'),
Markup('<a href="http://gu3.co.jp/">gu3</a>'),
]
ctxt = {'w' : 'World!', 'b': b, 'l': l}
return render_to_response('testapp/index.html', ctxt)

テンプレートファイルの作成

templates/testapp/index.html を作成
XMLでテンプレートが書けます


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/" py:strip=""
xmlns:xi="http://www.w3.org/2001/XInclude"
>
<head>
</head>
<body>
<h1>Hello, ${w}</h1>

<py:choose test="b()">
<hr py:when="True" color="#00FF00" />
<hr py:otherwise="" color="#FF0000" />
</py:choose>

<xi:include href="testapp/include.html" />

<ul py:for="link_tag in l">
<li>${link_tag}</li>
</ul>
</body>
</html>

インクルードされるテンプレートファイルの作成

templates/testapp/include.html


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
py:strip=""
>
The quick brown fox.
</html>

動作確認


$ python manage.py runserver
して、ブラウザで http://127.0.0.1:8000/testapp/ にアクセスを行います。