Featured image of post Mastering Hugo template whitespaces on external scripts integrity tags

Mastering Hugo template whitespaces on external scripts integrity tags

Since SRI(Subresource Integrity)-Checks are used more and more , Hugo also supports this, but unfortunately the space character can become a problem in multi-line template files.

you may find your template having a file themes/THEMENAME/data/external.yaml that looks like e.g.

Vibrant:
- src: /assets/cdn_jsdelivr_net/npm/node-vibrant_VERSION_3.1.5/dist/vibrant.min.js
integrity: sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g=
type: script

PhotoSwipe:
- src: /assets/cdn_jsdelivr_net/npm/photoswipe_VERSION_4.1.3/dist/photoswipe.min.js
integrity: sha256-ePwmChbbvXbsO02lbM3HoHbSHTHFAeChekF1xKJdleo=
type: script
defer: true
...

The Problem - no Space between attributes

The Problem arising with the renderer not rendering spaces looks like a complain from Firefox no Space between attributes in source code view, or external javascript failing to load ..

Failed Renderer

so the resulting html is invalid

     <script            integrity="sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g="src="/assets/cdn_jsdelivr_net/npm/node-vibrant_VERSION_3.1.5/dist/vibrant.min.js"            crossorigin="anonymous"   defer="false"   >            </script><script type="text/javascript" src="/ts/main.js" defer ></script>

( you clearly see that e.g. the src= part is missing spaces )

Here the trick was to create the file layouts/partials/helper/external.html and use a " after the {{- with .integrity -}} and leave the tag before “unclosed”:

{{- $List := index .Context.Site.Data.external .Namespace -}}
{{- with $List -}}
{{- range . -}}
{{- if eq .type "script" -}}
<script   src="{{ .src }}" defer="{{ default false .defer }}
{{- with .integrity -}}"   integrity="{{ . }}"  crossorigin="anonymous"      > </script>
{{- else -}}"  crossorigin="anonymous"      >            </script>
{{- end -}}
{{- else if eq .type "style" -}}
<link rel="stylesheet"                 href="{{ .src }}
{{- with .integrity -}}"                 integrity="{{ . }}"     crossorigin="anonymous"  >
{{- else -}}"   crossorigin="anonymous"  >
{{- end -}}
{{- else -}}
{{- errorf "Error: unknown external resource type: %s" .type -}}
{{- end -}}
{{- end -}}
{{- else -}}
{{- errorf "Error: external resource '%s' is not found" .Namespace -}}
{{- end -}}

So the renderer does what it should and finally puts the right spaces:

        </div>
        <script   src="/assets/cdn_jsdelivr_net/npm/node-vibrant_VERSION_3.1.5/dist/vibrant.min.js" defer="false"   integrity="sha256-5NovOZc4iwiAWTYIFiIM7DxKUXKWvpVEuMEPLzcm5/g="  crossorigin="anonymous"      > </script><script type="text/javascript" src="/ts/main.js" defer ></script>

<script>

OK Renderer

      ...