{{ $fig := newScratch }}
{{ if .Get "caption" }}
  {{ $fig.Set "caption" (.Get "caption") }}
{{ else if .Get "alt" }}
  {{ $fig.Set "caption" (.Get "alt") }}
{{ end }}
<!-- resolve absolute image path -->
{{ $permalink := $.Page.Permalink }}
{{ $image := .Get "src" }}
{{ $image_link_absolute := (findRE "^/" $image) }}
<figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
  {{ if .Get "link"}}
    <a href="{{ .Get "link" }}"
    {{ with .Get "target" }} target="{{ . }}"{{ end }}
    {{ with .Get "rel" }} rel="{{ . }}"{{ end }}>
  {{ end }}
  <img
      {{ if $image_link_absolute }}
        src="{{ $image | absURL }}"
      {{ else }}
        src="{{ (printf "%s%s" $permalink $image) }}"
      {{ end }}
        {{ if .Get "alt" }}alt="{{ .Get "alt" | markdownify | plainify }}"
        {{ else if .Get "caption" }}alt="{{ .Get "caption" | markdownify | plainify }}"
        {{ end }}
        {{ with .Get "align" }}align="{{ . }}"{{ end }}
        {{ with .Get "height" }}width="{{ . }}"{{ end }}
        {{ with .Get "width" }}width="{{ . }}"{{ end }} style="max-width: 100%;"
         />
  {{ if .Get "link"}}</a>{{ end }}
  <!-- caption and attr-->
  {{ if ($fig.Get "caption") }}
    <figcaption>
      <span class="img--caption">
        Figure {{ $.Page.Scratch.Get "fig" }}. {{ $fig.Get "caption" | markdownify | plainify }}
        {{ if .Get "attr" }}
          [{{- with .Get "attrlink"}}<a href="{{ . }}">{{ end }}{{ .Get "attr" | markdownify }}{{ if .Get "attrlink"}}</a>{{ end -}}]
        {{ end }}
      </span>
    </figcaption>
  {{ end }}
</figure>
{{ .Page.Scratch.Add "fig" 1 }}
{{ $fig.Delete "caption"}}
