Weekday as int for calendar sheet

I’m trying to build a calendar month view in hugo, e.g. something like this:

     January 2022
 M  T  W  T  F  S  S
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

For this, I need to get the Weekday of a date as an int between 1 and 7, i.e. I need to find out that “2022-01-01” was a 6 for Saturday to start the calendar sheet on the correct weekday.

("2022-01-01" | time).Weekday correctly returns Saturday, but as a string, not as an int. Different go tutorials mention to simply cast time.Weekday to int, but doing int ("2022-01-01" | time).Weekday in hugo unfortunately results in an error:

error calling int: unable to cast 6 of type time.Weekday to int

Ironically, it already displays the weekday as a number in the error message, but seems unable to return it programmatically. What am I doing wrong?

I ran into this cast limitation a while ago, and worked around it with:

{{ now.Weekday | printf "%d" | int }}

Upstream issue:
https://github.com/spf13/cast/issues/139

2 Likes

Wow, that’s incredibly neat! I was hoping for exactly something like this! Thanks a lot!

For the record: In the meantime, I experimented with an ugly workaround based on this idea by creating data/weekdays.yml in my themes folder, containing

Monday: 1
Tuesday: 2
Wednesday: 3
Thursday: 4
Friday: 5
Saturday: 6
Sunday: 7

Afterwards, it was possible to get the weekday as an int by something like this:

index $.Site.Data.weekday (string now.Weekday)

But I’d rather not convert the integer weekday to an english language string just to map it back to an integer, that seems inefficient and error-prone. So I like @jmooring’s idea a lot better!

I’m wondering if that wouldn’t be better handled by a JavaScript function at run time? Of course, if you need only a single month or a small number of them and they do not change, Hugo can do that.

It’s just that I’m not a big fan of JavaScript and I want to avoid it wherever possible :slight_smile: In my opinion, it’s much cooler to have all this stuff statically generated - after all, that’s what Hugo is for. In this case, I think it’s perfectly fine to go without JavaScrip, 12 monthly pages per year seem okay to me to generate. However, I’m also planning to do daily archives, and I still have to find a solution for that.

FIxed in deps: Update github.com/spf13/cast v1.4.1 => v1.5.0 by bep · Pull Request #9878 · gohugoio/hugo · GitHub

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.