テンプレートディレクトリの設定はどうすればいいの?
すでに http://[host]/sample/top/ で sample/views.py の top() モジュールが呼ばれるようになっている、とする。あとテンプレートディレクトリ(になる予定)の中に top.html ファイルが設置されている、とする。
で、やりたいことは top() モジュールが template/tpl/top.html を表示みたいな感じのこと。
ROOT_PATH = os.path.dirname(__file__) TEMPLATE_DIRS = ( os.path.join(ROOT_PATH, 'templates'), os.path.join(ROOT_PATH, 'templates/tpl'), )
-
- 3. sample/views.py を開く
- 4. 以下の内容を追記する
from django.template import Context, loader def top(request): t = loader.get_template('top.html') c = Context() return HttpResponse(t.render(c))
- 注意点
- テンプレートファイルを探す順番は setting.py 内で設定された TEMPLTE_DIRS の記載順になっている。
(例)
# setting.py ROOT_PATH = os.path.dirname(__file__) TEMPLATE_DIRS = ( os.path.join(ROOT_PATH, 'templates'), os.path.join(ROOT_PATH, 'templates/tpl'), )
となっていて、templates/test.html と templates/appl/test.html が存在する場合、
loader.get_template('test.html')
と記述すると、以下の順番でマッチするファイルを返す
1 : templates/test.html 2 : templates/appl/test.html