在Django模板文件中訪問數據

問題描述:

在Django的HTML模板文件中,我們如何訪問View視圖函數傳進來的變量呢?

使用方法總結:

1、訪問變量:

{{ variable_name }}

2、for循環

{% for post in posts %}
//其他代碼
{% endfor %}

3、if分支結構

{% if tag %}
標籤列表頁:{{ tag.name }}
{% elif  category %}
分類列表頁:{{ category.name }}
{% else %}
首頁
{% endif %}

4、訪問Post實例對象中的字段

// title字段
{{ post.title }}
// 訪問一對一外鍵category的name字段
{{ post.category.name }}
// 訪問多對多外鍵tag,這個時候需要藉助for循環
{% for tag in post.tag.all %}   // 先獲取所有的tag,然後借用for循環訪問每一個tag
	{{ tag.id }}
	{{ tag.name }}
{% endfor %}

5、block的使用
在base.html模板中定義block :

// base.html
{% block block_name %}
{% endblock %}

在list.html模板中,繼承base.html模板

{% extends "./base.html" %}

然後就可以在list.html模板中重寫該block了。

{% block block_name %}
<h2>{{ post.title }}</h2>
<hr/>
<p>
    {{ post.content }}
</p>
{% endblock %}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章