標籤:
安裝Django時會自動安裝Jinja2,用於模板渲染.
static、templates在project中的位置:appname - templates/static - appname
使用時只需像這樣:"blog/blog.html"、"blog/css/bootstrap.min.css"、"blog/img/bg.jpg",Django會自動到各自的目錄中去尋找相應的檔案
每個app都保持這種結構,可以避免名字衝突
編寫blog/views.py
from django.shortcuts import renderdef blog(request): #第一個參數必須有(一般叫request) return render(request, ‘blog/blog.html‘)
Jinja基本文法執行個體
<!-basic.html->
<DOCTYPE html>
<html lang="en">
<head>
{% block title %} <!-可在子類中替換的區塊->
<title>Homepage</title>
<% endblock %>
<meta charset="UTF-8">
{% load staticfiles %} <!-載入和使用靜態檔案,也可以直接 href=‘blog/css/bootstrap.min.css‘ ->
<link rel="stylesheet" type="text/css" href="{% static ‘blog/css/bootstrap.min.css‘ %}">
</head>
<body>
{% block content %} <!-可在子類中替換的區塊->
{% endblock %}
</body>
</html>
<!-blog.html->
{% extends "blog/basic.html" %} <!-繼承basic.html模板中的所有內容->
{% block title%} <!-替換父類模板中title區塊的內容->
<title>My Blog</title>
{% endblock %}
{% block content %}
{% for post in object_list %} <!-for、if的使用->
{% if {{ post.name} == ‘zoro‘ %} <!-變數的使用->
<p>{{ post.date|date:"Y-m-d" }}</p> <!-使用過濾->
{% endif %}
{% endfor %}
{% endblock %}
Django -- Templates