I have concern with the following behaviour of imageConfig
vs fileExists
and give a workaround:
The issue
TL;DR fileExists
looks in the theme’s static
directory as well as project root static
dir but imageConfig
only looks in project root static
dir.
Reproducing
Given a file that is in a theme module’s static
directory (apple-touch-icon.png
), a site in subdirectory of the theme (called exampleSite
),
using `replacements` to import the development theme into the site (in a `config.yaml)`
module:
replacements: "gitlab.com/danielfdickinson/dfd-hugo-theme-zen -> ../.."
imports:
- path: gitlab.com/danielfdickinson/dfd-hugo-theme-zen
mounts:
- source: archetypes
target: archetypes
- source: assets
target: assets
- source: i18n
target: i18n
- source: layouts
target: layouts
- source: static
target: static
mounts:
- source: assets
target: assets
- source: i18n
target: i18n
- source: layouts
target: layouts
- source: static
target: static
a site parameter named image
with the value `apple-touch-icon.png
The following (condensed version of the real code, originally part of the Zen theme by @frjo) in a partial for <head>
:
…
{{ $src := .Param "image" -}}
{{ if and $src (fileExists (path. Join "/static" $src)) -}}
{{ with (imageConfig (path.Join "static" $src)) -}}
{{ $realwidth .Width -}}
{{ $realheight .Height -}}
{{ end -}}
…
then hugo v0.111.3-5d4eb5154e1fed125ca8e9b5a0315c4180dab192+extended windows/amd64 BuildDate=2023-03-12T11:40:50Z VendorInfo=gohugoio
throws the error:
…
error calling imageConfig: open C:\Users\DanielDickinson\Build\hugo-dfd-sites\dfd-hugo-theme-zen\exampleSite\static\apple-touch-icon.png: The system cannot find the file specified.
…
Workaround
I have created the following workaround for now:
{{ $srcPath := path.Join "/static" $src -}}
{{ $srcDir := path. Dir $srcPath -}}
{{ $dirFiles := readDir $srcDir -}}
{{ $fileInDir := in $dirFiles (path. Base $srcPath) -}}
{{ if and $src (fileExists (path.Join "/static" $src)) $fileInDir -}}
{{- with (imageConfig (path.Join "static" $src)) -}}
{{ $realwidth = .Width -}}
{{ $realheight = .Height -}}
{{ end -}}
{{ end -}}
which builds without errors and seems to be working as expected.
Questions
@jmooring Is this difference between fileExists
and imageConfig
(and apparently readDir
) expected, or should I create a minimal reproducible test case and file a GitHub bug report?
I’ve run out of time to push the workaround and the version with issues until later tonight, but will do that.