Djangoテンプレートの使い方と設定方法

Djangoのテンプレート機能とはなにか?と基本的な使い方について紹介します。

目次

Djangoのテンプレート機能とは?

Djangoでのテンプレート(Template)とは、Webページをどのように見せるかを制御するファイル郡のことです。

DjangoではテンプレートファイルのHTMLファイルを使ってWeb画面を表示するのです。

一般的なHTMLファイルと違うところは、Djangoのテンプレートはデータの受け取り、if、for文などの制御文や独自のブロック構文を使うことができます。

このHTMLファイルの書き方は特殊であるため、次の章から書き方をレクチャーしていきます。

テンプレートを使うための準備

テンプレートを使う準備は以下になります。

  • アプリの作成
  • アプリのインストール
  • テンプレートファイルの指定
  • プロジェクト名/urls.pyの設定

アプリの作成方法は以下になります。

python manage.py startapp アプリ名

サンプルコードは以下になります。

python manage.py startapp hello

そうするとファイルの構造は以下の様になります。

mysite/
  manage.py
  mysite/
    __init__.py
    settings.py
    urls.py
    asgi.py
    wsgi.py
  hello/
    migrations/
       __init__.py
    views.py
    tests.py
    models.py
    apps.py
    admin.py
    __init__.py

その後、プロジェクト名/プロジェクト名/settings.pyに行って、settings.pyを編集してください。

INSTALLED_APPSにさっきのアプリを追加します。

サンプルの場合はmysite/mysite/settings.pyでございます。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # ここに追加します。
    'hello',
]

これでアプリのインストールは完了です。

次にテンプレートのファイルを優先に検索する場所を設定します。

これも先ほどと同じsettings.pyで行います。

もしmanage.pyと同じディレクトリの下にtemplatesフォルダを作成した場合以下の様に追加します。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # ここに追加
            os.path.join(BASE_DIR, 'templates'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

以上のAPP_DIRSはアプリの下のtemplatesフォルダも検索するかしないかを表してます。

Trueの場合は検索します。

上記の場合、先にmanage.pyと同じディレクトリの下のtemplatesフォルダを検索し、

その後、アプリフォルダの下のtemplatesフォルダを検索します。

もしアプリディレクトリの下にtemplatesフォルダを作り、

manage.pyと同じディレクトリには何も作らない場合、

何もしなくても大丈夫です。ただしAPP_DIRSがTrueになっている事を確認してください。

二つ方法がありますが、分かりやすいほうでテンプレートを作ってくれれば大丈夫です。

今回は第二の方法はアプリディレクトリの下にtemplatesフォルダを作り、urls.pyを編集します。

以下のようにに編集します。

from django.contrib import admin
from django.urls import path,include
# pathの後ろにincludeを追加
urlpatterns = [
    path('admin/', admin.site.urls),
  # この下の行を追加
    path('hello/', include('hello.urls')),
]

これで準備完了です。次はテンプレートの表示に行きましょう。

テンプレートの表示

今Djangoファイル構造は以下になっております。

mysite/
  manage.py
  mysite/
  __init__.py
  settings.py
  urls.py
  asgi.py
  wsgi.py
  hello/
    migrations/
      __init__.py
    views.py
    tests.py
    models.py
    apps.py
    admin.py
    __init__.py

まず初めにhello/の下にtemplatesというフォルダを作ってください。

その後その中にhtmlファイル、index.htmlという名のhtmlを作成します。 index.htmlの内容は以下の様になります。

<html>
<head>
  <meta charset=UTF-8>
  <title>Template test</title>
</head>
<body>
  <p>This is a Django template test</p>
</body>
<html>

その後hello/の下のviews.pyを編集してください 編集前は以下の様になっております。

from django.shortcuts import render
# ここから下の部分を追加
def show_index(request):
    return render(request, 'index.html')

そして最後にhello/の下にurls.pyを作成します。 中は空ですので以下の様に編集してください。

from django.urls import path
from . import views

urlpatterns = [
    path('',views.show_index, name='index')
]

これで完了です。 そしてDjangoを起動してみましょう。 以下のコマンドを打ちます。

python manage.py runserver 0:8000

その後<ipアドレス>:8000/helloに行ってください。

テンプレートが表示されてます。

テンプレートにデータを渡す

テンプレートにはデータを渡すことができます。渡す方法は以下になります。

アプリの中のviews.pyを以下の様に編集します。

return render(request,'htmlファイル',辞書型のデータ)

テンプレート(htmlファイル)の中は以下の様になります。

{{views.pyの辞書のキー}}

サンプルは以下になります。

まずhello/templates/の中のindex.htmlを以下の様に編集してください。

<html>
<head>
  <meta charset=UTF-8>
  <title>Template test</title>
</head>
<body>
  <p>{{message}}</p>
  <p>This is a Django {{function}} test</p>
</body>
<html>

そしてDjangoを実行してみてみましょう。

python manage.py runserver 0:8000

{{}}で囲った部分は表示されておりません。

これはviews.pyからデータを渡されてないからなのです。

次にmysite/hello/views.pyを編集してください。

編集後は以下の様になります。

from django.shortcuts import render

def show_index(request):
    params={
        'message':'Hello',
        'function':'template',
    }
    return render(request, 'index.html',params)

その後もう一度起動してみてください。

python manage.py runserver 0:8000

データを渡すことに成功しました!

{{message}}の部分はHelloで,{{function}}の部分はtemplateになっております。

テンプレートでif文、for文の使い方

テンプレートのif文の方法は以下になります。

{% if 条件 %}
表示するコンテンツ
{% elif 条件 %}
表示するコンテンツ
.
.
{% elif 条件 %}
表示するコンテンツ
{% else %}
{% endif %}

条件文はpythonのif文とほぼ同じでございます。(インデントが必要ない、条件などは同じ)

ではサンプルコードに移ります。

mysite/hello/templates/のindex.htmlを以下の様に編集してください。

<html>
<head>
  <meta charset=UTF-8>
  <title>Template test</title>
</head>
<body>
  <p>{{message}}</p>
  <p>This is a Django {{function}} test</p>
  {% if num == 1 %}
  <p>Number is 1</p>
  {% else %}
  <p>Number is not 1</p>
  {% endif %}
</body>
<html>

そしてviews.pyを以下の様に編集してください。

from django.shortcuts import render

def show_index(request):
    params={
        'message':'Hello',
        'function':'template',
        'num':1,
    }
    return render(request, 'index.html',params)

そしてDjangoを起動してみましょう。

python manage.py runserver 0:8000

すると以下になります。

Number is 1 になっております。

ではviews.pyを以下に編集してください。

from django.shortcuts import render

def show_index(request):
    params={
        'message':'Hello',
        'function':'template',
        'num':2,
    }
    return render(request, 'index.html',params)

そしてDjangoを起動してみましょう。

python manage.py runserver 0:8000

Number is not 1が表示されてます。

ちゃんとif文が動いておりますこれでif文が動く事を確認しました。

次はfor文を確認しましょう for文の使い方は以下です。

{% for 文 %}
.
.
.
{% endfor %}

では実際に試してみましょう。

mysite/hello/templates/のindex.htmlを以下の様に編集してください。

<html>
<head>
  <meta charset=UTF-8>
  <title>Template test</title>
</head>
<body>
  <p>{{message}}</p>
  <p>This is a Django {{function}} test</p>
  {% for i in num %}
  {{i}}
  {% endfor %}
</body>
<html>

そしてviews.pyを以下の様に編集してください。

from django.shortcuts import render

def show_index(request):
    params={
        'message':'Hello',
        'function':'template',
        'num':range(6),
    }
    return render(request, 'index.html',params)

そしてDjangoを起動してみましょう。

python manage.py runserver 0:8000

ちゃんとfor文が動いてるのが確認できました!

テンプレートの継承

テンプレートは継承する事ができます。方法は以下になります。

親のhtml:

{% block ブロック名 %}
{% endblock %}

子のhtml:

{% extends ベースのhtml %}

では実際に見てみましょう まずはmysite/hello/templatesの下にbase.htmlをお造りください。base.htmlは以下の様になります。

<html>
<head>
  <meta charset=UTF-8>
  <title>Template test</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>

その後、index.htmlを以下の様に編集してください

{% extends base.html %}
{% block content %}
  <p>{{message}}</p>
  <p>This is a Django {{function}} test</p>
  {% for i in num %}
  {{i}}
  {% endfor %}
This is a inheritance test
{% endblock %}

そしてDjangoを起動してみましょう。

python manage.py runserver 0:8000

すると以下になります。

継承成功です!!!

よかったらシェアしてね!
  • URLをコピーしました!
目次