Django-4.2博客開發教程:首頁功能實現(十一)

一、首頁菜單的實現

 如上圖首頁菜單紅框中是動態生成的,所以這些數據的來源是數據庫中。

在首頁視圖函數裏,查詢出所有的文章分類名稱,在模板中加載這些數據就顯示爲上圖菜單。

blog/views.py

def test(request):
    all_Class = Classes.objects.all()#通過Classes表查出所有分類
    #把查詢出來的分類封裝到字典中
    context = {
            'all_Class': all_Class,
        }
    return render(request, 'blog/test.html', context)#把字典傳到index.html頁面

blog/test.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
</head>
<body>
  {% for c in all_Class %}

    <h3>{{ c.class_name }}</h3>

    {% endfor %}
</body>
</html>

 效果如圖,查出來的

二 、整個流程是這樣的:

1. blog/views.py 通過 all_Class 查詢數據庫得到分類的所有信息
2. blog/views.py 通過render 將context 字典傳給'blog/test.html'模板
3. blog/test.html 通過這個標籤接收數據 {% for c in all_Class %}
4. blog/test.html 通過雙大括號加上單個對象的字段名 <h3>{{ c.class_name }}</h3>,最終展示到瀏覽器中



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章