flask系列---首页内容展示(十三)

版权声明: https://blog.csdn.net/JENREY/article/details/85628830

发布问答界面与功能以及完成了,我们要把用户发布的内容在首页展示出来,逻辑也是很简单,在请求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,通过authoravatar_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;
}

猜你喜欢

转载自blog.csdn.net/JENREY/article/details/85628830