もっと手軽にdjangoのテンプレートを使いたい。

djangoのtemplateをもっと手軽に、具体的にはviewsとtemplate分けたりせずに使いたい。*1

要求

  • webAPIの動作確認をするために、いちいち、ファイル分けたくない。

もっと手軽に利用したい。

問題

ところがドキュメントの通りに書くとimport Errorを返してしまう。
環境変数などが色々定義されていないせいらしい。
普通にmanage.pyなどから使う場合は、settingsを読み込むのでこのようなerrorは返さない。

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

django.conf.settings.configure()を事前に呼んであげると良い。

code

以下のようにすると使えた。

import django.template as tmpl
from django.conf import settings 
settings.configure() 
t = tmpl.Template("hey {{ name }},  {{ message }}")
c = tmpl.Context({"name": "foo",  "message": "what's up?"})

print t.render(c)
hey foo,  what's up?

*1:jinja2とか違うtemplate engineつかえと言う話もある。