該實戰教程基于菜鳥教程,菜鳥教程可參考:http://www.runoob.com/django/django-template.html
模闆文法,每個架構都有其支援的模闆文法,Django的模闆文法在我看來與vue.js倒有一些相似處
,比如它們的模闆文法中參數為{{parm}}。
本篇所用到的例子,仍然基于實戰(一)
在HelloWorld(該檔案夾有urls.py)目錄下新增templates檔案夾,在templates新增hello.html
<html>
<head>
</head>
<body>
<h1>{{ hello }}</h1>
</body>
</html>
修改settings.py檔案夾
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
這個修改位置就好比Java的SSM開發中的視圖解析器(可以是freemarker,可以是jsp,也可以是volocity等)。
修改view.py
# -*- coding: utf-8 -*-
#from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
context = {}
context['hello'] = 'Hello World!'
return render(request, 'hello.html', context)
這裡的context與Java中的Map或者是Model倒也幾分相似。
簡單的說,都是來傳回給前端資料渲染用的。
最後顯示為:

這裡說一下Django的模闆語言
程式設計語言什麼if-else ,if-else if -else,for 等等是十分比較常用的。
而Django作為Python的web架構同樣如此。
(1)if/else或if/elseif/else标簽
{% if condition %}
... display
{% endif %}
或
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}
(2)for标簽
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
(3)ifequal/ifnotequal 标簽
{% ifequal %} 标簽比較兩個值,當他們相等時,顯示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
下面的例子比較兩個模闆變量 user 和 currentuser :
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}
和 {% if %} 類似, {% ifequal %} 支援可選的 {% else%} 标簽:8
{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% else %}
<h1>No News Here</h1>
{% endifequal %}
(4)注釋标簽
{# 這是一個注釋 #}
(5)過濾器
模闆過濾器可以在變量被顯示前修改它,過濾器使用管道字元,如下所示:
{{ name|lower }}
{{ name }} 變量被過濾器 lower 處理後,文檔大寫轉換文本為小寫。
過濾管道可以被* 套接* ,既是說,一個過濾器管道的輸出又可以作為下一個管道的輸入
(6)include 标簽
{% include "nav.html" %}
同jsp中的<%include file="nav.html"%>
要說差別除了Python與Java的差別外,那就隻能說{和%差別。