I have to admit that originally I was kind of skeptical about keeping images & content together.
But after seeing the demo that @bep made for .Resources
, I can’t wait until the release.
To prepare for it I have already began reorganizing my static assets alongside content files.
But the interesting thing is that it is possible to publish a Hugo project with the new organization right now!
Here is my semi-magical shortcode:
{{% asset_img "1.jpg" %}}
And here are the contents of asset_img.html
:
<!-- image -->
<figure>
{{ $base := $.Page.Permalink | replaceRE "([^/]*)/$" "" }}
{{ $link := $.Page.RelPermalink | replaceRE "([^/]*)/$" "" }}
{{ $file := .Get 0 }}
{{ $.Scratch.Add "src" $link }}
{{ $.Scratch.Add "src" $file }}
{{ $src:= $.Scratch.Get "src"}}
{{ $config := imageConfig (printf "/content/%s" $src) }}
<img class="thumb b-lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="{{ $base }}{{ .Get 0 }}" alt="{{ with $.Page.Params.title}}{{.}}{{end}}" height="{{$config.Height}}" width="{{$config.Width}}" />
<noscript>
<img src="{{ $base }}{{ .Get 0 }}" alt="{{ with $.Page.Params.title}}{{.}}{{end}}"/>
</noscript>
</figure>
<!-- image -->
First of all I have set a variable called $base
with the .Permalink
of the post in which the shortcode resides. In this variable I have also piped a Regular Expression to remove the final part of the permalink after the last slash to get the content directory where both content and image reside.
So http://localhost:1313/blog/2017/07/after-as-before/
becomes http://localhost:1313/blog/2017/07/
Then I am constructing the img data-src with "{{ $base }}{{ .Get 0 }}"
That’s straightforward enough. The above permalink variable alongside a shortcode positional parameter.
Now I always use imageConfig
in my img shortcodes because I use modal plugins like Photoswipe that require width and height values.
THe imageConfig
function first reads a file from the file system to determine its dimensions and Hugo outputs the img URL later.
Therefore I set a second variable called $link
to get the page’s RelPermalink
because if I used the absolute Permalink
I would get a broken URL.
Again I performed the same RegEx as before, in this variable, to remove the last part and point to the content directory.
Then I set the following variables (the first one gets the shortcode filename and then with .Scratch
I combine it with the RelPermalink
variable)
{{ $file := .Get 0 }}
{{ $.Scratch.Add "src" $link }}
{{ $.Scratch.Add "src" $file }}
{{ $src:= $.Scratch.Get "src"}}
And finally I use the $src
variable to get the image’s dimensions with imageConfig
{{ $config := imageConfig (printf "/content/%s" $src) }}
That’s it! It’s very versatile in the sense that I can prepare for .Resources
and have a functional Hugo site right now.