Top / Programming / Python / Django TIPS / 描画結果を文字列として取得する

描画結果を文字列として取得する

テンプレートの処理結果を、画面に描画せず、文字列と取得する方法の解説です。

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

def index(request):
    t = loader.get_template('bbs/index.html')
    c = Context({'name': u'Alice',})
    html_str = t.render(c)

django.template.loader.get_templte(テンプレート名)は、指定したテンプレート名に対応したTemplateオブジェクトを返します。

t = loader.get_template('bbs/index.html')

Contextは、テンプレートへ置き換える値を設定します。

c = Context({'name': u'Alice',})

Templateオブジェクトのrenderメソッドは、受け取ったコンテキストを元にレンダリングを行います。

html_str = t.render(c)

更新履歴