From ebb449ce69694b5db788b2c6e4ac64596bb9c97a Mon Sep 17 00:00:00 2001 From: Rohan Verma Date: Sat, 16 Nov 2019 16:16:10 +0530 Subject: [PATCH] blog: hugo group by year --- .gitignore | 4 +- .../2019/2019-11-15-hugo-group-by-year.md | 70 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 content/blog/2019/2019-11-15-hugo-group-by-year.md diff --git a/.gitignore b/.gitignore index 89ff0a6..9f956e5 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,6 @@ Desktop.ini $RECYCLE.BIN/ # OSX -.DS_Store \ No newline at end of file +.DS_Store + +.vscode \ No newline at end of file diff --git a/content/blog/2019/2019-11-15-hugo-group-by-year.md b/content/blog/2019/2019-11-15-hugo-group-by-year.md new file mode 100644 index 0000000..fb116b7 --- /dev/null +++ b/content/blog/2019/2019-11-15-hugo-group-by-year.md @@ -0,0 +1,70 @@ ++++ +title = "Creating archive pages grouped by year in Hugo" +date = 2019-11-15T15:30:03+05:30 +draft = false +tags = ["hugo", "blog", "golang"] +categories = ["tutorials"] +type = "post" +url = "blog/2019/11/15/archive-pages-group-by-year-hugo" +author = "Rohan Verma" ++++ + +I was on the hunt to find out how to organize my [blog](/blog_list) and +[project](/project) archive pages by year in Hugo. After being unable to find +any easy solutions I decided I would sit down and write the go template to +render these pages myself. The idea was simple, iterate over the list divided +by year into sub lists and render tables, but it turned out to be a bit tricky. + +Here is the template, hope it is useful for someone who wants to have a similar +page. + +```html +{{ define "title" -}} + Blog List | {{ .Site.Title }} +{{- end }} +{{ define "header" }} + {{ partial "masthead.html" . }} +{{ end }} +{{ define "main" }} +
+

{{ .Title }}

+
+ +
+ {{ $prev := 3000}} + {{range .Site.RegularPages}} + {{if .Date}} + {{if gt $prev (.Date.Format "2006")}} + {{ if ne $prev 3000}} + + {{ end }} +

{{ .Date.Format "2006" }}

+ + {{end}} + + + + + {{ $prev = .Date.Format "2006"}} + {{end}} + {{end}} +
{{.Date.Format "02 Jan"}}{{.Title}}
+
+ +{{ end }} +{{ define "footer" }} + {{ partial "powered-by.html" . }} +{{ end }} +``` + +The above template loops through all the blogs (having a date) and renders +multiple tables +which are grouped by the year. We render `h2` tags with the year if the previous +year is greater than the current year. Followed +by a `` tag having each next blog rendered as a row in the table. The +previous seen date is updated for the next iteration. In each iteration, before +rendering the table tag we check if the previous date was greater than the date +or`3000` (an arbitrarily high year) which we set as the previous seen year +before starting the loop, to decide if we want to close the table tag. In the +next iteration, the previous year will be the same as the current year, and so +we can continue to render rows. \ No newline at end of file