Skip to content

侧边栏开发

CSR 渲染 - 推荐文章展示

查询文章点击量数据,并返回

python
# filename: forum/apis/index.py
@index_api.get("/hot_article")
def get_hot_article():
    q = db.select(ArticleORM)
    q = q.order_by(ArticleORM.clicks.desc())
    q = q.limit(10)
    ret = db.session.execute(q).scalars()

    return {
        "code": 0,
        "msg": "获取热门文章成功",
        "results": [r.as_json() for r in ret]
    }

前端部分 部分

javascript
$.ajax({
  url: "/api/v1/hot_article",
  type: "get",
  success: function (res) {
    res.results.forEach((article, index) => {
      $(".rank_list a")
        .eq(index)
        .text(article.title)
        .attr("href", `/article/${article.id}`);
    });
  },
});

SSR 渲染 - 推荐文章展示

后端先查询热门文章数据,然后传递到 jinja2 模版,之后进行渲染。

html 模板渲染

html
<!--排行榜栏-->
<div class="rank">
    <div class="rank_title">
        <h3>热门文章</h3>
    </div>
    <div class="rank_list">
        {% for article in hot_article_list %}
            <a href="/article/{{ article.id }}">{{ article.title }}</a>
        {% endfor %}
    </div>
</div>