richcms源码分析之:上一条下一条数据的实现

richcms是一个可以免费使用的golang cms系统,使用golang+msyql开发完成,可以去官网下载安装:https://www.richcms.net/down,本文章介绍richcms的源码实现:上一条和下一条数据的实现。

一、数据库查询的代码:

// LastNext 按某文章时间取上一篇和下一偏文章
func (m *Article) LastNext(created int) (last *Article, next *Article, err error) {
	db := mysql.GetORM()
	data := make([]*Article, 0)
	sqlStr := fmt.Sprintf("(select id,title,created from tbl_article  where created<%d and state=%d order by created desc  limit 1 ) union (select id,title,created from tbl_article  where created>%d and state=%d order by created asc  limit 1) order by created asc", created, int(enum.ArticleStateEnable), created, int(enum.ArticleStateEnable))
	err = db.Table(m.TableName()).Raw(sqlStr).Scan(&data).Error
	length := len(data)
	switch length {
	case 2:
		last = data[0]
		next = data[1]
	case 1:
		info := data[0]
		if info.Created > created {
			last = info
		}
		if info.Created < created {
			next = info
		}
	}
	return
}

二、用户端页面函数调用的实现代码:

func LastAndNext(created int) (ta *view.TwoArticle) {
	last, next, _ := new(model.Article).LastNext(created)
	ta = new(view.TwoArticle)
	articleDao := new(dao.ArticleDao)
	ta.Last = new(model.Article)
	ta.Next = new(model.Article)
	ta.Last = articleDao.ConvertItem(last)
	ta.Next = articleDao.ConvertItem(next)
	return
}

三、注册为golang的模板函数代码:

	r.AddFuncMap("fn_article_last_next", LastAndNext)                     //上一篇和下一篇,传入文章的created时间

四、在html模板页面上调用的源码:

以下代码根据你的html模板具体实现,只处只是richcms官网的模板调用实现。

                <div class="prev-next-post">
                    <div class="row my-5">
                        <% $ta:=fn_article_last_next .article.Created %>
                        <!-- Previous article -->
                        <div class="col-12 col-sm-6 prev-post-start">
                            <span class="d-block text-muted mb-2">上一篇文章</span> «
                            <% if $ta.Last %>
                            <a href="<% $ta.Last.Link %>" rel="prev"><% $ta.Last.Title %></a>
                            <% else %>
                            没有上一篇..
                            <% end %>
                        </div>
                        <!-- Next article -->
                        <div class="col-12 col-sm-6 next-post-end">
                            <span class="d-block text-muted mb-2">下一篇文章</span>
                            <% if $ta.Next %>
                            <a href="<% $ta.Next.Link %>" rel="next"><% $ta.Next.Title %></a>
                            <% else %>
                            没有下一篇了..
                            <% end %>
                            »
                        </div>
                    </div>
                </div>