Setting script type inside condition causes an error

Template:

<script {{ if true }} type="" {{ end }}></script>

Error:

render of "page" failed:
"/Users/Will/Developer/paige/layouts/_default/baseof.html:33:11":
execute of template failed at <partial "paige/scripts.html" $page>:
error calling partial:
"/Users/Will/Developer/paige/layouts/partials/paige/scripts.html:34:3":
execute of template failed at <partial "paige/script.html" (dict "src" "_paige/bootstrap/bootstrap.bundle.js")>:
execute of template failed:
html/template:partials/paige/script.html:1:14:
{{if}} branches end in different contexts:
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementNone <nil>},
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementScript <nil>}
render of "home" failed:
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementNone <nil>},
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementScript <nil>}
failed to render pages:
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementNone <nil>},
{stateTag delimNone urlPartNone jsCtxRegexp attrNone elementScript <nil>} 

If you remove the condition around the type attribute, or rename type to something else, then there’s no error.

Env:

❯ hugo env
hugo v0.111.3+extended darwin/amd64 BuildDate=unknown
GOOS="darwin"
GOARCH="amd64"
GOVERSION="go1.20.2"
github.com/sass/libsass="3.6.5"
github.com/webmproject/libwebp="v1.2.4"
github.com/sass/dart-sass-embedded/protocol="1.2.0"
github.com/sass/dart-sass-embedded/compiler="1.59.2"
github.com/sass/dart-sass-embedded/implementation="1.59.2"

If you want to repro it yourself, replace the content of paige/script.html at b381f8742d2be6b39c44713a8c0d303cfca864a8 · willfaught/paige · GitHub with the above template.

This is Go’s html/template package doing its thing…

If you want to pass in an arbitrary value:

{{ $type := "foo" }}
<script {{ with $type }}{{ printf " type=%q" . | safeHTMLAttr }}{{ end }}></script>

If you want to use a literal, it cannot be arbitrary or an empty string.

<script {{ if true }} type="" {{ end }}></script>                <!-- error -->
<script {{ if true }} type="xxx" {{ end }}></script>             <!-- error -->
<script {{ if true }} type="module" {{ end }}></script>          <!-- ok -->
<script {{ if true }} type="text/javascript" {{ end }}></script> <!-- ok -->

This behavior is as-designed per:
https://github.com/golang/go/issues/57136

That issue’s resolution didn’t address the problem, which the author pointed out. The author worked around it by hard-coding the attribute value to “module”, however the author is wrong in that there are other valid values for the type attribute, such as “text/javascript”, “importmap”, etc.

Thanks for explaining the situation. This appears to be a Go issue, not a Hugo issue.

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