Top / Programming / Python / Django TIPS / テンプレートファイルを指定して描画する

テンプレートファイルを指定して描画する

ビューからテンプレートファイルを指定して描画する方法を解説します。

テンプレートファイルの保存場所の設定

テンプレートファイルの保存場所を設定します。

settings.pyを編集します。

project/
├__init__.py
├manage.py
├settins.py <-このファイルを編集する
├urls.py
└application/
  ├__init__.py
  ├models.py
  └views.py

TEMPLATE_DIRSの設定を修正します。

import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates')
)

任意のディレクトリを指定することができます。
この例では、project/templatesディレクトリに設定しています。

ビューのコード

from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse

def index(request):
    t = get_template('example.html')
    html = t.render(Context({'name': u'Alice'}))
    return HttpResponse(html)

この例では、テンプレートファイルにtemplates/example.htmlを使用しています。

project/
├__init__.py
├manage.py
├settins.py
├urls.py
├application
│├__init__.py
│├admin.py
│├models.py
│└views.py
└templates/ <-settings.pyで設定したテンプレート配置ディレクトリ
  └example.html <-テンプレートファイル

ショートカット

テンプレートの読み込みからレンダリング結果を返すまでの処理は共通の流れです。
Djangoでは、一連の流れをショートカットする関数を提供しています。

from django.shortcuts import render_to_response

def index(request):
    return render_to_response('example.html', {'name': u'Alice'})

render_to_response関数は、1つ目の引数にテンプレート名を、2つめの引数にContextの辞書を渡します。
2つめの引数を省略した場合、render_to_response関数は空の辞書を使用します。

組み込み関数locals()

Pythonの組み込み関数locals()はローカル辞書を返します。
Contextに渡す辞書に使用すると、関数内で作成したローカル変数を同じ名前で渡すことができます。

def index(request):
    current_date = datetime.datetime.now()
    return render_to_response('example.html', locals())

更新履歴