djangoでtailwind導入して、見た目を整える。
参考URL
1 2 3 4 5 6 7 8 |
# django向けtailwindをインストール pip install django-tailwind django-admin startproject myproject # tailwindベースのdjangoアプリを生成。 # 最後にアプリ名を入力しなければ、themeがデフォ python manage.py tailwind init |
settings.pyに追記
1 2 3 4 5 6 7 8 9 10 11 |
INSTALLED_APPS = [ # ... 'tailwind', # django-tailwind パッケージ。tailwindエンジン 'theme', # 実際のTailwind の設定やカスタムCSSを書く場所 ] TAILWIND_APP_NAME = 'theme' #Tailwindを使うアプリ INTERNAL_IPS = [ '127.0.0.1', ] # npmのパス NPM_BIN_PATH = "C:\\Program Files\\nodejs\\npm.cmd" |
1 2 |
# TailwindCSSの依存関係をインストール(npm installを実行) python manage.py tailwind install |
デフォルトでは theme/templates/base.htmlが生成される。
親テンプレート(base.html)をextendした子テンプレート(index.html)で値を渡せるように、{% block ブロック名 %}{% endblock %}を挿入しておく
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
{% load static tailwind_tags %} <!DOCTYPE html> <html lang="ja"> <head> <title>{% block title %}{% endblock %}</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> {% tailwind_css %} </head> <body class="bg-gray-50 font-serif leading-normal tracking-normal"> <div class="container mx-auto"> <section class="p-4"> <h1 class="text-5xl">{% block h1 %}{% endblock %}</h1> </section> {% block main %}{% endblock %} </div> </body> </html> |
下準備が終わったので、自作アプリを生成
1 |
python manage.py startapp myapp |
myapp追記を忘れないように!!
1 2 3 4 5 6 |
INSTALLED_APPS = [ # ... 'tailwind', # django-tailwind パッケージ。tailwindエンジン 'theme', # 実際のTailwind の設定やカスタムCSSを書く場所 'myapp' # 忘れないように追加!! ] |
自作アプリ用の子テンプレートを生成。親テンプレートのブロック名に合わせて記述する
myapp/templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{% extends "base.html" %} {% block title %}Django Tailwind{% endblock %} {% block h1 %}Django + Tailwind{% endblock %} {% block main %} <div class="max-w-sm rounded overflow-hidden shadow-lg border mb-2"> <div class="px-6 py-4"> <div class="font-bold text-xl mb-2">カードタイトル</div> <p class="text-gray-700 text-base">カード本文</p> </div> <div class="px-6 pt-2 pb-2"> <a href="http://example.com/" class="bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-blue-700 mr-2 mb-2">Read more</a> </div> </div> {% endblock %} |
myapp/views.pyで制御
1 2 3 4 |
from django.shortcuts import render def index(request): return render(request, 'index.html') |
myproject/urls.pyで、ルーティング
1 2 3 4 5 6 |
from django.urls import path from myapp.views import index urlpatterns = [ path('', index), ] |
1 2 3 4 |
# 内部で npm run dev が実行 python manage.py tailwind start # webサーバ python manage.py runserver |