Hugo: How to get the date field off of a page

Published: 2020-02-17 14:59:35 -0500 -0500

Reading time: 1 mins (165 words)

Tags: hugo date

problem

I’m writing a template for my posts (in layouts/_default/single.html) and want to be able to access the date field from its frontmatter. How can I use the date in my template.

solution

The date field is available to you via .Date in your template.

So to access it inside your template you could do

{{ .Date }}

If you weren’t using this in a single layout but were instead using this in a list or something, you can still access the date field via .Date in the same way, assuming you set the context (accessed via .) to be of page type.

Here’s an example of accessing the date field of a page while iterating over all pages in your site - you’ll note that we can still access this in the same way because the range iterator implicitly sets its inner context to the current element in the iteration:

{{ range .Site.RegularPages }}
    My page published at: {{ .Date }}
{{ end }}

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus