django備忘録9 Django Templates - Include, Inheritance, Blocks
参照サイト
try-django-1.8 というjustinさんのサイトを参考に学習を進めています。 https://www.youtube.com/watch?v=KsLHt3D_jsE
markdown記法の備忘録用のリンク Markdown記法 チートシート - Qiita
djangoのtemplates言語, includeを活用する
- bootstrapのコピペした雛形の中から、navbarの部分をカット→navbar.htmlにペーストする。
- base.html(navbarのコピペ元)に、
{% include 'navbar.html' %}
と記載すると、navbar.htmlの内容を表示してくれる。
djangoのtemplates言語, blockを活用する
- base.htmlを開く→''をカット→home.html に貼り付ける
- base.html のclass junbotronがあったところに、以下のような感じでblock文を挿入
<div class="container"> {% block content %} {% endblock %} </div> <!-- /container -->
home.htmlのうち、base.htmlのblockの箇所に表示させたい内容の箇所を、 ' {% block content %}' ' {% endblock %}' で挟む。
views.pyのrenderingのtemplatesを、"home.html"に変更する。
home.html の一番上に、{% extends "base.html" %} と挿入する。これにより、base.html をinheritanceできる!
ただし、base.htmlで ' {% block content %}'、' {% endblock %}'した範囲に、home.htmlで、' {% block content %}'、' {% endblock %}'した範囲が代入される感じになる。 ちょっとわかりづらいので、自分の中では、block content を一つの変数として、home.htmlのblockcontent が、base.htlml のblockcontentに代入されていると考えている。
上記と同様に、'{% block junbotoron %}'、' {% endblock %}' などで、base.htmlに代入できる!
さらに同様に base.html
{% block head_title %} {% endblock %}
home.html
{% block head_title %}Welcome | {% endblock %}
とかで、タイトルも変更できる。
{{ block.super }} について
多分、extends元の「親block」を引っ張ってこれる奴。
{% block jumbotron %} {{ block.super }} {% endblock %}
include と、blockを使って、base.htmlを分解していく
head_css.html
{% load staticfiles %} <!-- Bootstrap core CSS --> <!-- <link href="../../dist/css/bootstrap.min.css" rel="stylesheet"> --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- <img src="{% static "my_app/example.jpg" %}" alt="My image"/> --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <!-- <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> --> <link href="{% static 'css/ie10-viewport-bug-workaround.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <!-- <link href="navbar-static-top.css" rel="stylesheet"> --> <link href="{% static 'css/navbar-static-top.css' %}" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="../../assets/js/ie-emulation-modes-warning.js"></script> <link href="{% static 'js/ie-emulation-modes-warning.js' %}" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]-->
この時、link hrefにstatic関数を使っているので、{% load staticfiles %}を忘れない。
次に、base.htmlのカットした部分に、{% include "head_css.html" %}を挿入 ここまでで、移管作業が一区切り
javascriptの部分も同様に、カット→新規ファイル javascript.html作成→{% include "javascript.html" %}
てな感じで、bootstrapも分解すると色々デザインとかに幅が出るというお話でした。