本文へスキップ
BecomeCoder

Djangoコース · 第3章 テンプレート · レッスン14

render とテンプレートの実プロジェクト配置

ローカル実施

導入

このコースではテンプレートを Python の文字列で書いてきましたが、本物のプロジェクトでは .html ファイルとして置きます。その置き場所と、ビューからの呼び方を知っておきましょう。

説明

実際のプロジェクトでは、テンプレートは各アプリの templates/ フォルダに置きます。

blog/
├── views.py
└── templates/
    └── blog/
        ├── base.html
        └── post_list.html

settings.pyTEMPLATES"APP_DIRS": True にしておくと、Django が各アプリの templates/ を自動で探してくれます。

# settings.py(抜粋)
TEMPLATES = [{
    "BACKEND": "django.template.backends.django.DjangoTemplates",
    "DIRS": [],
    "APP_DIRS": True,   # 各アプリの templates/ を自動で探す
    "OPTIONS": {"context_processors": [...]},
}]

ビューからは render ショートカットで呼びます。

# blog/views.py
from django.shortcuts import render

def post_list(request):
    posts = ["最初の記事", "2番目の記事"]
    return render(request, "blog/post_list.html", {"posts": posts})

render(request, テンプレート名, コンテキスト辞書) の3つを渡すだけ。これは、このコースで書いてきた次のコードとまったく同じことをしています。

# render が内部でやっていること(イメージ)
from django.template.loader import get_template
from django.http import HttpResponse

def post_list(request):
    template = get_template("blog/post_list.html")
    html = template.render({"posts": ["..."]}, request)
    return HttpResponse(html)

post_list.html の中身は、これまで学んだテンプレート言語そのものです。

{% extends "blog/base.html" %}
{% block content %}
  <h1>記事一覧</h1>
  <ul>
    {% for post in posts %}
      <li>{{ post }}</li>
    {% endfor %}
  </ul>
{% endblock %}

静的ファイル(CSS・画像・JS) は各アプリの static/ に置き、テンプレートの先頭で {% load static %} してから {% static 'blog/style.css' %} のように参照します。本番公開時は python manage.py collectstatic で1か所に集めて配信します(第7章で触れます)。

つまり、このコースで文字列として書いてきたテンプレートを .html ファイルに移し、render(request, "ファイル名", {...}) で呼ぶだけで、そのまま本物のプロジェクトになります。