欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

13.首页内容展示

发布时间:2025/3/20 编程问答 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 13.首页内容展示 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

发布问答界面与功能以及完成了,我们要把用户发布的内容在首页展示出来,逻辑也是很简单,在请求home.html的时候,从Questions中获取所有的数据,在home.html中使用for循环将每一个对象的内容写上去。
将home视图函数改写如下:

@app.route('/') def home():questions = Questions.query.order_by(Questions.create_time.desc()).all()return render_template('home.html', questions=questions)

与之前相比,增加了一行从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; }

总结

以上是生活随笔为你收集整理的13.首页内容展示的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。