13.首页内容展示
發布問答界面與功能以及完成了,我們要把用戶發布的內容在首頁展示出來,邏輯也是很簡單,在請求home.html的時候,從Questions中獲取所有的數據,在home.html中使用for循環將每一個對象的內容寫上去。
將home視圖函數改寫如下:
與之前相比,增加了一行從Questions中獲取所有數據,并按創建時間倒序排列,因為網頁的內容一般都是從新到舊的。然后把獲取的數據用questions這個參數傳入home.html,因此我們要在home.html增加處理questions的代碼,如下:
{% extends 'base.html' %}{% block page_name %}首頁{% endblock %}{% block body_part %} <ul> {% for question in questions %}<li><div>{{ question.title }}</div><div>{{ question.content }}</div><div>{{ question.author.username }}</div><div>{{ question.create_time }}</div></li> {% endfor %} </ul> {% endblock %}這里也很好理解,從questions中遍歷所有的數據,每一個for對應一個li標簽,li標簽了顯示問題的標題、內容、作者及創建時間,其中獲取作者的username是通過6.ORM與SQLAlchemy (2) - 模型關系與引用提到的反向引用實現的。此時主頁的內容顯示如下:
再隨便發布一條,首頁也會增加,并且新發布的會位于最上面:
到現在展示的功能已經算是實現了,我們再美化一下html,通過author的avatar_path字段把頭像也顯示出來,最終的效果如下:
附上html代碼:
{% extends 'base.html' %}{% block static_files %} <link rel="stylesheet" href="{{ url_for('static',filename='css/home.css') }}"/> {% endblock %}{% block page_name %}首頁{% endblock %}{% block body_part %} <ul> {% for question in questions %}<li><div class="avatar-group"><img src="{{ url_for('static',filename=question.author.avatar_path) }}" class="img-circle"/></div><div class="question-group"><p class="question-title"><a href="#">{{ question.title }}</a></p><p class="question-content">{{ question.content }}</p><p class="question-info"><span class="question-author">{{ question.author.username }}</span><span class="question-time">{{ question.create_time }}</span></p></div></li> {% endfor %} </ul> {% endblock %}對應的home.css代碼:
.body-container ul{list-style: none;padding: 0 10px; }.body-container li{overflow: hidden;padding: 10px 0;border-bottom: 1px solid #eee; }.avatar-group{width: 38px;float: left; }.img-circle{width: 38px; }.question-group{margin-left: 10px;width: 525px;float: left; }.question-title{font-weight: 900;color: #259; }.question-content{text-indent: 2em; }.question-info{text-align: right; }.question-author{margin-right: 10px; }總結
- 上一篇: 腾讯下载视频转换MP4
- 下一篇: 云天视角-浅谈闭包