Why does this not work? (dynamic resource bundling)

The following loop grows a slice of resources referenced from a data file. After the loop we call resources.Concat to produce one output file.

  {{ resources.Get "sass/theme.scss" | toCSS | slice | .Scratch.Set "css_file" }}
  {{ range .Site.Data.assets.scss }}
    {{ $.Scratch.Get "css_file" | append (resources.Get . | toCSS | slice) | $.Scratch.Set "css_file" }}
  {{ end }}
  {{ $style := .Scratch.Get "css_file" | resources.Concat "assets/css/style.css" | fingerprint }}

data/assets.yml looks like this:

  - sass/a/style_a.scss
  - sass/b/style_b.scss

It works, yes, but it took me ages to discover the subtle requirement of | slice inside the loop. Without it, Hugo fails with the message: error calling append: append element type mismatch: expected resource.Resource, got *resource.transformedResource. According to the docs though, append should just append slices or elements equally fine. Furthermore, AFAIK, all elements have exactly the same type. Does slice change the element type??

1 Like

The error you got is because of a bug I introduced in 0.49.1 (or 0.49, not sure) and fixed in 0.49.2.

That said, I would suggest that you … scratch .Scratch and simply to something ala:

{{ $css := resources.Get "sass/theme.scss" | toCSS | slice }}
{{ range .Site.Data.assets.scss }}
$css = $css | append (resources.Get .) }}
{{ end }}
{{ $style :=  $css | resources.Concat "assets/css/style.css" | fingerprint }}

With no guarantee that I spelled the above correct …

Confirmed. I’m running 0.49, so guess I’ll have to leave the | slice in for now. That’s OK.

And the variable assignment without .Scratch works a charm. Thanks!

1 Like