## 變量和索引
~~~
{{ 變量名 }}
{{ info_dict.site }} key使用點進行索引 info_dict.items info_dict.keys info_dict.values
{{ info_list.0 }} 使用點運算進行索引
~~~
---
## 邏輯運算
模板中的邏輯操作
```
# 這些比較都可以在模板中使用,比如
==, !=, >=, <=, >, < :
and, or, not, in, not in
```
>[danger] 注意:比較符號前后必須有至少一個空格!
## 標簽
```
# 對模板中的block標簽進行填充
{% extends 'template.html' %}
# 導入html代碼
{% include 'template.html' %}
{% block title %}默認值或者替換值{% endblock %}
```
## for循環
```
{% for item in list %}
{{ item }}
{% endfor %}
```
#### empty
```
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>抱歉,列表為空</li>
{% endfor %}
```
### for循環中的變量
```
forloop.counter # 索引從 1 開始算
forloop.counter0 # 索引從 0 開始算
forloop.revcounter # 索引從最大長度到 1
forloop.revcounter0 # 索引從最大長度到 0
forloop.first # 當遍歷的元素為第一項時為真
forloop.last # 當遍歷的元素為最后一項時為真
forloop.parentloop # 用在嵌套的 for 循環中,獲取上一層 for 循環的 forloop
```
## if判斷
```
{% if 判斷 %}
{% else %}
{% endif %}
```
## url
```
<a href="{% url 'add' 4 5 %}">URL</a>
```
還可以使用 as 語句將內容取別名(相當于定義一個變量),多次使用(但視圖名稱到網址轉換只進行了一次)
```
{% url 'some-url-name' arg arg2 as the_url %}
<a href="{{ the_url }}">鏈接到:{{ the_url }}</a>
```
## 模板中 獲取當前網址,當前用戶
如果不是在 views.py 中用的 render 函數,是 render_to_response 的話,需要將 request 加入到 上下文渲染器(點擊查看詳細)
### Django 1.7 及以前 修改 settings.py
如果沒有 TEMPLATE_CONTEXT_PROCESSORS 請自行添加下列默認值,是否缺少最后一行。
```
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
)
```
然后在 模板中我們就可以用 request 了。
### Django 1.8 及以后 修改 settings.py
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
'django.template.context_processors.request',
...
],
},
},
]
```
#### 獲取當前用戶
```
{{ request.user }}
```
如果登陸就顯示內容,不登陸就不顯示內容:
```
{% if request.user.is_authenticated %}
{{ request.user.username }},您好!
{% else %}
請登陸,這里放登陸鏈接
{% endif %}
```
#### 獲取當前網址
```
{{ request.path }}
```
或者
```
{{ request.path_info }}
```
#### 獲取當前 GET 參數
```
{{ request.GET.urlencode }}
```
### 合并到一起用的一個例子
~~~
<a href="{{ request.path }}?{{ request.GET.urlencode }}&delete=1">當前網址加參數 delete</a>
~~~