Skip to content

Instantly share code, notes, and snippets.

@budparr
Last active September 23, 2020 15:39
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save budparr/771a2fb2165cf23a75ae10b5fc9d1ea4 to your computer and use it in GitHub Desktop.
Save budparr/771a2fb2165cf23a75ae10b5fc9d1ea4 to your computer and use it in GitHub Desktop.
Hugo "figure" shortcode that works with https://github.com/aFarkas/lazysizes and uses `markdownify` for title and caption #gohugo
<!-- image -->
<figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
{{ with .Get "link"}}<a href="{{.}}">{{ end }}
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt"}}{{.}}{{else}}{{ .Get "caption" }}{{ end }}" {{ end }}{{ with .Get "width" }}width="{{.}}" {{ end }} class="lazyload" />
<noscript>
<img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt"}}{{.}}{{else}}{{ .Get "caption" }}{{ end }}" {{ end }}{{ with .Get "width" }}width="{{.}}" {{ end }}/>
</noscript>
{{ if .Get "link"}}</a>{{ end }}
{{ if or (or (.Get "title") (.Get "caption")) (.Get "attr")}}
<figcaption>{{ if isset .Params "title" }}
<h4>{{ .Get "title" | markdownify }}</h4>{{ end }}
{{ if or (.Get "caption") (.Get "attr")}}<p>
{{ .Get "caption" | markdownify }}
{{ with .Get "attrlink"}}<a href="{{.}}"> {{ end }}
{{ .Get "attr" }}
{{ if .Get "attrlink"}}</a> {{ end }}
</p> {{ end }}
</figcaption>
{{ end }}
</figure>
<!-- image -->
@budparr
Copy link
Author

budparr commented Oct 6, 2017

To use this shortcode you have to have Lazysizes installed. See that repo for instructions.

To use this, put the above code into the file:
layouts/shortcodes/figure.html

And use the shortcode as a replacement for the built-in Hugo version, like this:
{{< figure src="/media/spf13.jpg" title="Steve Francia" >}}

@brennanangel
Copy link

Thanks for making this!
Racking my brain, is any reason why the <noscript> doesn't have {{- with .Get "height" }} height="{{ . }}"{{ end -}}?
It shows up here: https://github.com/gohugoio/hugo/blob/master/tpl/tplimpl/embedded/templates/shortcodes/figure.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment