Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created May 26, 2020 10:34
Show Gist options
  • Select an option

  • Save morgyface/4095abb91f2b22fcb27624c4ac3678c8 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/4095abb91f2b22fcb27624c4ac3678c8 to your computer and use it in GitHub Desktop.
11ty | Dates | Nunjucks
<span class="approval__date">{{ item.designDate.toDateString().slice(4, -5) }}</span>
@morgyface
Copy link
Author

morgyface commented May 26, 2020

Eleventy dates

I've spent a while messing with dates in 11ty and Nunjucks and here is what I've discovered so far.

Content dates

There's a fair bit you can do with the dates associated with the content files themselves, which is indeed useful.

Dates within templates

Working with dates within templates themselves is a little more limited out of the box. For example, calculating an age or displaying dates in different formats isn't simple, well, not to me as someone with limited JavaScript knowledge.

Front matter to JavaScript object

However, I have discovered you can turn a date (in the format YYYY-MM-DD) from front matter data into a date string using toDateString. This returns a date in the following readable format Tue May 06 2020, once in this format it can be manipulated to suit. So in the above code we use Nunjucks' builtin slice filter to remove the first 4 characters and the last 5, which returns just May 06.

Further possibilities

I'm sure more can be achieved here, for example, once in a JavaScript format can we use sum to calculate a time period?

Global data

Dates are more workable when taken from front matter data. When they're taken from global data files, it appears as though they lack the versatility.

More here once I have time to play.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment