HUGO

Casting a frontmatter date param in a where statement?

Trying to get date from map inside of an array in front matter for comparison but can’t seem to get it to work out.

E.g.

  {{range $p :=  (where (where .Params.featured_post.post_options "visible" "==" true) "date" ">=" time.Now )}}
      <div class="flex flex-col w-1/3 p-10" >
          {{time time.Now}}
      </div>
  {{end}}

Front matter:

featured_post:
  post_options:
    - _option: custom
      title: 'Introducing my stuff'
      date: 2021-11-20 10:00:00 -0700

Feels like a small missing piece of the puzzle. I’ve tried casting it using

(time "date")

to no avail. Thanks for any tips and pointers on where to read.

Times aren’t first class citizens in YAML, so the date is interpreted as a string, making it a hassle to work with in scenarios like this.

With front matter in TOML…

+++
title = "Test"
date = 2021-01-01T00:00:00.000Z
draft = false

[[featured_post.post_options]]
_option = "custom"
date = 2021-11-16T15:20:23-08:00
title = "A"
visible = false

[[featured_post.post_options]]
_option = "custom"
date = 2021-11-17T15:20:23-08:00
title = "B"
visible = true

[[featured_post.post_options]]
_option = "custom"
date = 2021-11-19T15:20:23-08:00
title = "C"
visible = true

[[featured_post.post_options]]
_option = "custom"
date = 2021-11-20T15:20:23-08:00
title = "D"
visible = true
+++

Putting this in layouts/_default/single.html…

{{ $post_options := where .Params.featured_post.post_options "visible" true }}
{{ $post_options = where $post_options "date" "ge" now }}
<pre>{{ jsonify (dict "indent" "  ") $post_options  }}</pre>

Produces…

[
  {
    "_option": "custom",
    "date": "2021-11-19T15:20:23-08:00",
    "title": "C",
    "visible": true
  },
  {
    "_option": "custom",
    "date": "2021-11-20T15:20:23-08:00",
    "title": "D",
    "visible": true
  }
1 Like

Unfortunately I don’t have the luxury of switching from YAML. :frowning:

{{ $post_options := slice }}
{{ range where .Params.featured_post.post_options "visible" true }}
  {{ if ge (.date | time.AsTime) now }}
    {{ $post_options = $post_options | append . }}
  {{ end }}
{{ end }}
<pre>{{ jsonify (dict "indent" "  ") $post_options }}</pre>

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