Flask博客实战 - 实现文章列表页及详情页

实现分类列表页

在设计数据库字段的时候,我们将分类与文章设置为一对多关系,一个分类下可以有多篇文章,那么导航栏通过上一节我们已经实现了,那么这一节我们就实现每个分类下的文章列表页!

在app/blog/views.py中实现分类页视图

@bp.route('/category/')
def cates(cate_id):
    # 分类页
    cate = Category.query.get(cate_id)
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.filter(Post.category_id==cate_id).paginate(page, per_page=10, error_out=False)
    post_list = pagination.items
    return render_template('cate_list.html', cate=cate, post_list=post_list, cate_id=cate_id, pagination=pagination)

这个函数的逻辑也是在之前管理后台的时候多次实现,这里我们用了filter的查询方法根据url传进来的分类主键id来查询当前分类下的数据,并对其进行分页!

在app/blog/templates/中创建一个cate_list.html的模板文件

{% extends 'base.html' %}

{% block title %}{{ cate.name }}{% endblock title %}

{% block hero %}{% endblock hero %}

{% block box %}

    
        
            {% block breadcrumb %}
            
            {% endblock breadcrumb %}
        

        {% block cate_box %}
        {% for post in post_list %}
            
                

{{ post.title }}

{{ post.add_date }} {{ post.category.name }} {{ post.tags|join(',') }}

{{ post.desc }} {% endfor %} {% block pagination %} {% endblock pagination %} {% endblock cate_box %} asdas {% endblock box %}

该模板中我们查询出了刚才视图中返回的数据,并继承base.html实现了一个一本的样式!

  • 最终样式
Flask博客实战 - 实现文章列表页及详情页

实现文章详情页

在app/blog/views.py中实现文章详情页视图

@bp.route('/category//')
def detail(cate_id, post_id):
    # 详情页
    cate = Category.query.get(cate_id)
    post = Post.query.get_or_404(post_id)

    # 上一篇
    prev_post = Post.query.filter(Post.id < post_id).order_by(-Post.id).first()
    # 下一篇
    next_post = Post.query.filter(Post.id > post_id).order_by(Post.id).first()

    return render_template('detail.html', cate=cate, post=post, prev_post=prev_post, next_post=next_post)

这段代码不仅实现了文章详情页,还实现了上一篇及下一篇的功能!

通过url我们分别传入了分类cate_id以及当前文章post_id两个主键,之后根据这两个主键获取所属分类的及文章,代码如下:

cate = Category.query.get(cate_id)
post = Post.query.get_or_404(post_id)

在这里我们同时实现了详情页的上一篇及下一篇的功能,根据当前文章的id来判断筛选出上一篇和下一篇!代码如下:

# 上一篇
prev_post = Post.query.filter(Post.id < post_id).order_by(-Post.id).first()
# 下一篇
next_post = Post.query.filter(Post.id > post_id).order_by(Post.id).first()

在app/blog/templates/中创建一个detail.html的模板文件

{% extends 'cate_list.html' %}

{% block title %}
    {{ post.title }}
{% endblock title %}

{% block breadcrumb %}
    
{% endblock breadcrumb %}

{% block cate_box %}

    

{{ post.title }}

{{ post.add_date }} {{ post.category.name }} {{ post.tags|join(',') }}

{{ post.content|safe }}
{% if prev_post %} 上一篇:{{ prev_post.title }} {% endif %} {% if next_post %} 下一篇:{{ next_post.title }} {% endif %} {% endblock cate_box %}

增加导航菜单中的url

路径: app/blog/templates/base.html

{% for cate in categorys %}
    
        {{ cate.name }}
    
{% endfor %}

首页文章url完善

路径: app/blog/templates/base.html

{% for post in posts %}

    
        
            
Placeholder image

{{ post.title}}

{{ post.desc }}

{% endfor %}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章