In Go 1.23, you can now do "else with" logic branches in templates

From Go 1.23 Release Notes - The Go Programming Language :

text/template

Templates now support the new “else with” action, which reduces template complexity in some use cases.

Past: Support proposal to add "else with" like "else if" feature in templates

4 Likes

This is correct, but you need to wait for the next Hugo release (or build from source).

2 Likes

Does it work really? I tried modifying the code here css.TailwindCSS where {{ else }} {{ with . | fingerprint }} appears, to {{ else with . | fingerprint }} but it throws an error.

Error: template: 404.html:17: unexpected <with> in input

Using Hugo v0.147.5.

yes it works, if you use the else with for a with clause and not an if clause

    {{ with . | css.TailwindCSS $opts }}
      {{ if hugo.IsDevelopment }}
        <link rel="stylesheet" href="{{ .RelPermalink }}">
      {{ else }}                   <-- That's the else for the if clause, not the with
        {{ with . | fingerprint }}
          <link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
        {{ end }}
      {{ end }}
    {{ end }}

Then that seems like an omission in the accepted request since OP had suggested a mix of the two text/template: add "else with" like "else if" · Issue #57646 · golang/go · GitHub. I guess I can live with it rather than making a proposal in Go that may come to nought.

as I understood he requested the else with for a with clause. the other was stated as nice to have.

the Go team only implemented the first. which for me is ok to fulfill the issue.

in fact mixing if - which does not change context with with - which does – looks weird.

Just curious why would that be? Isnt the latest version of Hugo statically built with the corresponding latest version of Go at the time of release?

Probably. And if that’s the case, versions of Hugo compiled before Go 1.23 was available, will not contain features of Go 1.23. Hugo versions published after Go 1.23 is available, will be compiled with it and thus contain the features available with that Go version.

Seems quite logical to me.

2 Likes

Looking at the commit 2168c5b Upgrade to Go 1.23, for Hugo release 0.133.0 the else with construct has been available since Aug 18, 2024. Nice!!