Using "with" function on a json key with spaces

Hello - I have a json file data/seminars.json looking something like this:

[
  {
    "Id": 1,
    "Seminar Name": "Seminar ABC",
    "URL": "http://thesite.jp/seminar-abc"
  },
  {
    "Id": "2",
    "Seminar Name": "Seminar XYZ",
    "URL": null
  }
]

I have a shortcode layouts/shortcodes/showseminar.html which has something like this conceptually:

{{ $id := .Get 0 }}
{{ range where .Site.Data.seminars ".Id" $id }}
  <p>{{ with .SOMEKEY }}{{ . }}{{ end }}</p>
{{ end }}

… which I’ll call in my markdown like:

{{< showseminar 1 >}}
{{< showseminar 2 >}}

… as needed. I want to use with because there are occasionally nulls in the data like the URL in Id 2.

If I use {{ with .URL }} (or any other key with no spaces in it), the above concept works fine. If I try it with “.Seminar Name”, it fails because of the space. I’ve tried various variants:

<p>{{ with ."Seminar Name" }}{{ . }}{{ end }}</p>
<p>{{ with .'Seminar Name' }}{{ . }}{{ end }}</p>
<p>{{ with .Seminar+Name }}{{ . }}{{ end }}</p>
etc

… to no avail. Any idea how to specify a key that has a space, for use with with?

Hey Rick!

Have you tried with + index ?

{{ with (index . "Seminar Name") }}{{ . }}{{ end }}
2 Likes

Perfect, @regis, thanks!

1 Like

I needed to pull another field’s result in, as text to use in an <a> tag, within a with statement to get the URL. Scratch to the rescue. Set a scratch variable at the top of your range, using whatever field you need.

{{ $id := .Get 0 }}
{{ range where .Site.Data.seminars ".Id" $id }}
{{ $.Scratch.Set "urltext" (index . "URL Text")  }}
...

… then reference it:

...
<p>{{ with .URL }}
<a href="{{ . }}">{{ $.Scratch.Get "urltext" }}</a>
{{ end }}</p>