oinume journal

Scratchpad of what I learned

PyramidでJjinja2をテンプレートエンジンとして使う

Pythonネタ。最近PyramidというWebアプリケーションフレームワークを使い始めてる。

 

Pyramidはデフォルトで ChameleonMako というテンプレートエンジンが使えるが、自分は Jinja2 派なので、pyramid_jinja2というモジュールをインストールする。

 

インストール

 

pip install pyramid_jinja2

 

するだけでインストール完了。

 

使い方

Pyramidのアプリケーションディレクトリの下の __init__.py に以下を追記する。(myappの部分は自分のアプリケーション名に置き換える)

 

youapp/__init__.py

 

def main(global_config, **settings):

...

config = Configurator(settings=settings)

# Jinja2の設定

config.include('pyramid_jinja2')

config.add_jinja2_search_path('myapp:templates')

 

 

これで templates ディレクトリの下に拡張子が .jinja2 のファイルを置いておくとViewから使えるようになる。

 

myapp/__init__.py

 

def main(global_config, **settings):

config = Configurator(settings=settings)

...

config.add_route('jinja2_sample', '/jinja2_sample') # 追加

 

 

myapp/views.py

 

@view_config(route_name='jinja2_sample', renderer='templates/jinja2_sample.jinja2')

def jinja2_sample(request):

...

return { 'message': 'hello world!'}

 

 

yourapp/templates/jinja2_sample.jinja2

 

 

 

pyramid_jinja2 sample

 

 

{{ message }}

 

 

 

 

テンプレートファイルの拡張子を.htmlにしたい

余談だが、個人的にはテンプレートファイルの拡張子は .html にしたいので、ちょっとカスタマイズしてみた。具体的には yourapp/__init__.py の main のところに config.add_renderer('.html', 'pyramid_jinja2.renderer_factory') を追記しておくと拡張子が .html のファイルでもJinja2のテンプレートとして認識させることができる。

 

yourapp/__init__.py

 

def main(global_config, **settings):

...

config = Configurator(settings=settings)

# Jinja2の設定

config.include('pyramid_jinja2')

config.add_jinja2_search_path('yourapp:templates')

config.add_renderer('.html', 'pyramid_jinja2.renderer_factory') # これ

 

 

[tmkm-amazon]4797371595[/tmkm-amazon]