Support minification after `templates.Defer` execution

Currently, templates within a templates.Defer block are not minified.

For example, in the source for https://gohugo.io/:

  • layouts/baseof.html

    ...
    {{ with (templates.Defer (dict "key" "global")) }}
      {{ $t := debug.Timer "tailwindcss" }}
      {{ with resources.Get "css/styles.css" }}
        {{ $opts := dict "minify" (not hugo.IsDevelopment) }}
        {{ with . | css.TailwindCSS $opts }}
          {{ partial "helpers/linkcss.html" (dict "r" .) }}
        {{ end }}
      {{ end }}
      {{ $t.Stop }}
    {{ end }}
    ...
    
  • layouts/_partials/helpers/linkcss.html

    {{ $r := .r }}
    {{ $attr := .attributes | default dict }}
    
    {{ if hugo.IsDevelopment }}
      <link
        rel="stylesheet"
        href="{{ $r.RelPermalink }}"
        {{ template `render-attributes` $attr }}>
    {{ else }}
      {{ with $r | minify | fingerprint }}
        <link
          rel="stylesheet"
          href="{{ .RelPermalink }}"
          integrity="{{ .Data.Integrity }}"
          crossorigin="anonymous"
          {{ template `render-attributes` $attr }}>
      {{ end }}
    {{ end }}
    
    {{ define "render-attributes" }}
      {{- range $k, $v := . -}}
        {{- if $v -}}
          {{- printf ` %s=%q` $k $v | safeHTMLAttr -}}
        {{- else -}}
          {{- printf ` %s` $k | safeHTMLAttr -}}
        {{- end -}}
      {{- end -}}
    {{ end }}
    

Will be rendered without minification (the rest of the output remains unaffected):

Which I think is the expected behaviour, since by definition the function:

Defer execution of a template until after all sites and output formats have been rendered.

But, is there a way to perform minification after defer, or could this be supported in the future (even if it’s not essential)?

Edit: I should also add that while you can use {{- ... -}} to trim whitespace, the template will still be rendered as-is.

For example, code like:

<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous" />

Will not have the trailing slash (/>) removed by the minification process, even though it would be on non-deferred templates.

We will fix this. I noticed this issue when implementing the defer feature, but I decided to … push it. It’s not very hard.

2 Likes

Good to hear. Thank you.

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