排行展示:
排行相关:
后端Flask代码:
from . import blue_index
from flask import render_template, current_app, session, abort
from info.models import User, News
@blue_index.route("/")
def index():
"""
首页相关
点击排行
1.从数据库获取排序后的6条新闻
2.将数据返回到页面中
:return:
"""
# 获取点击排行前六条新闻
news_clicks_list = []
try:
news_clicks_list = News.query.order_by(News.clicks.desc()).limit(6)
except Exception as e:
current_app.logger.error(e)
context = {
"user": user,
"news_clicks_list": news_clicks_list,
}
# 3.返回信息到前端页面
return render_template("index.html", context=context)
HTML代码:
这里使用的是前后端不分离的写法:
<div class="rank_con fr">
<div class="rank_title">
<h3>点击排行</h3>
</div>
<ul class="rank_list">
{% for new in context.news_clicks_list %}
<li>
<span class="{{ loop.index | do_rank }}">{{ loop.index }}</span>
<a href="#">{{ new.title }}</a>
</li>
{% endfor %}
</ul>
</div>
自定义过滤器:
在 info/utils 下新建文件 comment.py:
def do_rank(index):
if index == 1:
return "first"
elif index == 2:
return "second"
elif index == 3:
return "third"
else:
return ""
注册过滤器:
在info/__init__.py,函数create_app中:
def create_app(config_name):
from info.utils.comment import do_rank
app.add_template_filter(do_rank)