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
- 下一篇: 云天视角-浅谈闭包