Can I copy file from assets to static on conditional build?

TLDR: Solved, I had the wrong path.

I’ve done a search in the forum to no avail. I’m wondering if I have a file somewhere, but probably in assets if I could copy that file over to static or… i guess not there, but have it in the public/ folder where i specify, only if the build is production mode.

I tried using resources.Copy but that gave me an error and anyway, for the resource function to happen, you have to use it or reference it in your template and I don’t need to. I tried referencing it within HTML comments, but as I said, it was an error.

Error

execute of template failed: template: partials/script.html:32:77: executing "partials/script.html" at <resources.Copy>: error calling Copy: runtime error: invalid memory address or nil pointer dereference

Template in script.html

{{ $jsmap := "" }}
{{ if hugo.IsProduction }}
{{ $scripts = $scripts | resources.Concat "/js/script.js" | minify | fingerprint "sha256" }}
{{ $jsmap = resources.Get "js/plugins/bootstrap/bootstrap.js.map" | resources.Copy "js/bootstrap.js.map" }}
{{ else }}
  {{ $scripts = $scripts | resources.Concat "/js/script.js" }}
{{ end }}

<!-- {{ $jsmap.RelPermalink }} -->

UPDATE: My apologizes. I had the resources.Get path wrong. And it shouldn’t have been in the production. Anyway, the correct path made it work as expected only when I included the <!-- {{ $jsmap.RelPermalink }} --> so it would actually copy the resource over.

You can also use the .Publish method…

{{ if hugo.IsProduction }}
  {{ (resources.Get "foo.txt").Publish }}
{{ end }}

How do you tell it where i the publish file structure to go? And do you still need to have a reference to it like RelPermalink?

By default it will use the resource path. If you want to explicity set the path:

{{ (resources.Get "foo.txt" | resources.Copy "foo/bar.txt").Publish }}

No.

2 Likes

Fantastic, thank you!

The above looks nice. Some day we may be tempted to create aliases for these so you can do:

{{ (get "foo.txt" | cp "foo/bar.txt").Publish }}
3 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.