How to use Hugo templating inside a file under the assets folder?

At the end of my baseof.html file, I have a script tag like this:

<script>
  // about 30 lines of code, of which the details are not important.
  aFunction() {
    {{ if not .Site.IsServer }}
      // A bit of analytics code which I only want in production
    {{ end }}
  }
</script>

Now, to save a millisecond or two, I’d like to move that JS under /assets/js/index.js
and use it like this:

{{ $mainJS := resources.Get "js/index.js" | minify }}
<script>
  {{ $mainJS.Content | safeJS }}
</script>

Which doesn’t work because the {{ if not .Site.IsServer }}...{{ end }} is not interpreted by Hugo; it literally comes out as {{ if not .Site.IsServer }}...{{ end }}.

Is there a way to run Hugo templating under the /assets folder?

You need to ExecuteAsTemplate: https://gohugo.io/hugo-pipes/resource-from-template/

1 Like

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