djangoのテンプレートをdjangoアプリ以外のところでも使う。

ちょっとしたファイルの生成などに,テンプレート使いたい。
djangoの環境があったので、このテンプレートをdjangoの開発以外でも使えたら楽。

重要なこと

  • includeタグが使えること。

ちょっと調べたら使えたのでメモ。

以下のようなファイル構成

.
├── hello.py
├── three_hello.py
└── xoo.py

xoo.pyからthree_hello.pyのテンプレートを呼び出して、hello worldのコードを作る。

three_hello.py

{% include "./hello.py" with name=foo %}
{% include "./hello.py" with name=bar %}
{% include "./hello.py" with name=baz %}

hello.py

print hello {{name}}

xoo.py

DJANGO_TEMPLATE_DIRSのタプルから、ディレクトリを探すらしい。

import django.conf as c
c.settings.configure()
c.settings.TEMPLATE_DIRS = (".", )
print c.settings.TEMPLATE_DIRS

from django.template.loader import render_to_string

print render_to_string("hello.py", dict(name="foo"))
print render_to_string("./three_hello.py", dict(foo="foo", bar="bar", baz="baz"))

## 実行結果
# print hello foo

# print hello foo

# print hello bar

# print hello baz