我的网站首页需要展示 3 个以上的分类,并且循环出每个分类下的文章并且限制 10 条.
我尝试使用全局变量去循环,但是出现的问题是 无法控制时间排序(已放弃)
我后来经过尝试 利用 分页的形式,把功能实现了,代码有点丑.我相信会有更 派森尼克的写法.请各位大大,指教一下…我实现的代码 如下
@index_bp.route('/')
def show_category():
category = Category.query.get_or_404(1) #指定分类
page = request.args.get('page', 1, type=int)
per_page = current_app.config['PER_PAGE']
pagination = Post.query.with_parent(category).order_by(Post.timestamp.desc(
)).paginate(page, per_page=per_page)
posts = pagination.items
category01 = Category.query.get_or_404(2) #指定分类
page = request.args.get('page', 1, type=int)
per_page = current_app.config['PER_PAGE']
pagination01 = Post.query.with_parent(category01).order_by(
Post.timestamp.desc(
)).paginate(page, per_page=per_page)
posts01 = pagination01.items
category02 = Category.query.get_or_404(3) #指定分类
page = request.args.get('page', 1, type=int)
per_page = current_app.config['PER_PAGE']
pagination02 = Post.query.with_parent(category02).order_by(
Post.timestamp.desc(
)).paginate(page, per_page=per_page)
posts02 = pagination02.items
return render_template('home/index.html', category=category,
pagination=pagination, posts=posts,
category01=category01, posts01=posts01,
pagination01=pagination01, category02=category02,
posts02=posts02, pagination02=pagination02)
模板实现的代码
{% for items in pagination.items %} 以此类推 #pagination01.items #pagination02.items
<li><a class="has-text-black" href="{{ url_for('.uuid_post',slug=slug) }}{{ items.slug }}" target="_blank ">{{ items.title|truncate(20) }}</a><span
class="is-pulled-right">[{{ items.timestamp.strftime
("%m-%d") }}]</span></li>
{% endfor %}
代码逻辑很乱.初学者…代码很难看.各位大大 见谅.