Access top-level variable in range

This works…

  {{ $myfilename := .File.BaseFileName }}
  {{ range .Site.Data.metadata }}
    {{if eq .url $myfilename }}
      <title>{{ .title }} - {{ $.Site.Title }}</title>
      <meta name="description" content="{{ .description }}" />
    {{end}}
  {{end}}

…but this doesn’t work:

  {{ range .Site.Data.metadata }}
    {{if eq .url .File.BaseFileName }}
      <title>{{ .title }} - {{ $.Site.Title }}</title>
      <meta name="description" content="{{ .description }}" />
    {{end}}
  {{end}}

Is there a solution without declaring a variable out of the range?

I tried {{if eq .url $.File.BaseFileName }} (with a dollar symbol) but this doesn’t work neither.

Background information

I have website with 1000+ pages and I want to store all titles and descriptions in a json file for easier maintaining. First I tried to access the json in the front matter but this doesn’t work.

My files

/data/metadata.json

[
  {
    "url": "post1",
    "title": "title1",
    "description": "description1"
  }
]

/content/post1.md

bla bla
{{ range where .Site.Data.metadata "url" .File.BaseFileName }}
  <title>{{ .title }} - {{ $.Site.Title }}</title>
  <meta name="description" content="{{ .description }}" />
{{ end }}
1 Like

It works, but I get the following warning:

WARN .File.BaseFileName on zero object. Wrap it in if or with: {{ with .File }}{{ .BaseFileName }}{{ end }}

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