From 6d4bbac08594ca6886c7a5da5c6acf6e62a5270c Mon Sep 17 00:00:00 2001 From: Xin Date: Tue, 2 Apr 2024 09:52:26 +0200 Subject: [PATCH] feat: support sort blog post list page (#348) --- exampleSite/hugo.yaml | 5 +++- layouts/blog/list.html | 7 +++--- layouts/partials/utils/sort-pages.html | 32 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 layouts/partials/utils/sort-pages.html diff --git a/exampleSite/hugo.yaml b/exampleSite/hugo.yaml index 0da0ad99..5b0776ac 100644 --- a/exampleSite/hugo.yaml +++ b/exampleSite/hugo.yaml @@ -136,7 +136,7 @@ params: flexsearch: # index page by: content | summary | heading | title index: content - # full | forward | reverse | strict + # full | forward | reverse | strict # https://github.com/nextapps-de/flexsearch/#tokenizer-prefix-search tokenize: forward @@ -147,6 +147,9 @@ params: blog: list: displayTags: true + # date | lastmod | publishDate | title | weight + sortBy: date + sortOrder: desc # or "asc" comments: enable: false diff --git a/layouts/blog/list.html b/layouts/blog/list.html index 376d5bc0..c67ebe27 100644 --- a/layouts/blog/list.html +++ b/layouts/blog/list.html @@ -7,7 +7,8 @@

{{ .Title }}

{{ .Content }}
- {{ range .Pages.ByDate.Reverse }} + {{- $pages := partial "utils/sort-pages" (dict "page" . "by" site.Params.blog.list.sortBy "order" site.Params.blog.list.sortOrder) -}} + {{- range $pages }}

{{ .Title }}

{{- if site.Params.blog.list.displayTags -}} @@ -25,9 +26,9 @@

{{ partial "utils/format-date" .Date }}

- {{ end }} + {{ end -}}
-{{ end }} +{{- end -}} diff --git a/layouts/partials/utils/sort-pages.html b/layouts/partials/utils/sort-pages.html new file mode 100644 index 00000000..4b8ee037 --- /dev/null +++ b/layouts/partials/utils/sort-pages.html @@ -0,0 +1,32 @@ +{{- $page := .page -}} +{{- $by := .by | default "weight" -}} +{{- $order := .order | default "asc" -}} + +{{- $pages := slice }} + +{{- if eq $by "weight" }} + {{- $pages = $page.Pages.ByWeight }} +{{- else if eq $by "date" }} + {{- $pages = $page.Pages.ByDate }} +{{- else if eq $by "title" }} + {{- $pages = $page.Pages.ByTitle }} +{{- else if eq $by "expiryDate" }} + {{- $pages = $page.Pages.ByExpiryDate }} +{{- else if eq $by "publishDate" }} + {{- $pages = $page.Pages.ByPublishDate }} +{{- else if eq $by "lastmod" }} + {{- $pages = $page.Pages.ByLastmod }} +{{- else if eq $by "linkTitle" }} + {{- $pages = $page.Pages.ByLinkTitle }} +{{- else if eq $by "length" }} + {{- $pages = $page.Pages.ByLength }} +{{- else }} + {{- warnf "sort-pages: unknown sort field %q" $by -}} + {{- $pages = $page.Pages }} +{{ end -}} + +{{- if eq $order "desc" }} + {{- $pages = $pages.Reverse }} +{{- end -}} + +{{- return $pages -}}