Skip to content

Commit

Permalink
feat: add new template functions (#316)
Browse files Browse the repository at this point in the history
* Fix update menu report update menu failed because of updateResult.RowsAffected=0

* Add template function

* Add template function
  • Loading branch information
Meepoljdx authored Oct 23, 2023
1 parent 2998933 commit 98d43b8
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func InitApp() *fx.App {
extension.RegisterToolFunc,
extension.RegisterPaginationFunc,
extension.RegisterPostFunc,
extension.RegisterStatisticFunc,
func(s *handler.Server) {
s.RegisterRouters()
},
Expand Down
22 changes: 22 additions & 0 deletions template/extension/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func RegisterPostFunc(template *template.Template, postService service.PostServi
p.addListPostByCategorySlug()
p.addListPostByTagID()
p.addListPostByTagSlug()
p.addListMostPopularPost()
}

func (p *postExtension) addListLatestPost() {
Expand All @@ -62,6 +63,27 @@ func (p *postExtension) addListLatestPost() {
p.Template.AddFunc("listLatestPost", listLatestPostFunc)
}

func (p *postExtension) addListMostPopularPost() {
listMostPopularPost := func(top int) ([]*vo.Post, error) {
ctx := context.Background()
posts, _, err := p.PostService.Page(ctx, param.PostQuery{
Page: param.Page{
PageNum: 0,
PageSize: top,
},
Sort: &param.Sort{
Fields: []string{"visits,desc"},
},
Statuses: []*consts.PostStatus{consts.PostStatusPublished.Ptr()},
})
if err != nil {
return nil, err
}
return p.PostAssembler.ConvertToListVO(ctx, posts)
}
p.Template.AddFunc("listMostPopularPost", listMostPopularPost)
}

func (p *postExtension) addGetPostCount() {
getPostCountFunc := func() (int64, error) {
ctx := context.Background()
Expand Down
34 changes: 34 additions & 0 deletions template/extension/statistic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package extension

import (
"context"

"github.com/go-sonic/sonic/model/dto"
"github.com/go-sonic/sonic/service"
"github.com/go-sonic/sonic/template"
)

type statisticExtension struct {
Template *template.Template
StatisticService service.StatisticService
}

func RegisterStatisticFunc(template *template.Template, statisticService service.StatisticService) {
s := &statisticExtension{
Template: template,
StatisticService: statisticService,
}
s.addGetStatisticsData()
}

func (s *statisticExtension) addGetStatisticsData() {
getStatisticsDataFunc := func() (*dto.Statistic, error) {
ctx := context.Background()
statistic, err := s.StatisticService.Statistic(ctx)
if err != nil {
return nil, err
}
return statistic, nil
}
s.Template.AddFunc("getStatisticsData", getStatisticsDataFunc)
}

0 comments on commit 98d43b8

Please sign in to comment.