Create shortcode for image legends (as ul list)

Since legends are often generated from data, it might make sense to store the legend data (json, toml, or yaml) adjacent to the image—both as page resources.

content/
└── posts/
    └── post-1/
        ├── images/
        │   ├── a.jpg
        │   ├── a.json  <-- legend data
        │   ├── b.jpg
        │   ├── b.json  <-- legend data
        │   └── c.jpg   <-- this image has no legend, and that's OK
        └── index.md

markdown

{{< foo "images/a.jpg" >}}

{{< foo "images/b.jpg" >}}

{{< foo "images/c.jpg" >}}
layouts/shortcodes/foo.html (something like...)
{{ with $path := .Get 0 }}
  {{ with $.Page.Resources.Get . }}
    <figure>
      <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
      {{ $legendData := print (strings.TrimSuffix (path.Ext $path) $path) ".json" }}
      {{ with $.Page.Resources.Get $legendData }}
        <figcaption>
          <ul class="legend">
            {{ range unmarshal . }}
              <li class="{{ .class }}">{{ .description }}</li>
            {{ end }}
          </ul>
        </figcaption>
      {{ end }}
    </figure>
  {{ else }}
    {{ errorf "The %q shortcode was unable to get %q. See %s" $.Name . $.Position }}
  {{ end }}
{{ else }}
  {{ errorf "The %q shortcode requires a single positional parameter. See %s" .Name .Position }}
{{ end }}


content/posts/post-1/images/a.json
[
  {
    "class": "blue",
    "description": "National recognition of animal sentience"
  },
  {
    "class": "green",
    "description": "Partial recognition of animal sentience"
  }
]

5 Likes