serhii.net

In the middle of the desert you can say anything you want

30 Mar 2022

Hugo better summary code

Hugo summaries are weird.

.Summary returns whatever summary it has, which is either the .. more .. tag, then everything before it gets returned including formatting, or whatever is set in the settings as summary length, while removing markdown formatting.

There was no easy way to get an auto-summary with preserved formatting, except manually adding stuff.

What I really wanted is to truncate posts manually when needed, and leave the rest in full by default while preserving formatting.

Setting the limit to infinite made .Summary returned the full post with stripped formatting.

(I needed this for footnotes in multiple posts all on the home page, they got mixed up and there were no clean solutions. The blackfriday renderer could fix this, but not the default goldmark, which I’m using for some layout issues it does better.)

After googling for better ways to truncate with preserved formatting, found Summary .Render · Scott Willsey

It has this code for a better summarization:

    {{ if gt ( sub (len (plainify .Content)) (len .Summary)) 10 }}
    {{ .Content | replaceRE "<sup.+>.+</sup>" "" | safeHTML | truncate (len .Summary) }}
    <p><i>(<a href="{{ .RelPermalink }}">Read More</a>)</i></p>
    {{ else }}
    {{ .Content | safeHTML }}
    {{- end -}}
    {{- if .Params.linkurl -}}
    <p><a href="{{ .RelPermalink }}"><i class="fas fa-level-down-alt fa-xs"></i>&ensp;Permalink</a></p>
    {{- end -}}

First up is an if statement that checks to see if the post even needs to be truncated into a summary or not, or whether it’s short enough to just show the whole post.

this works nice, but I wanted no summarization for

{{ if .Truncated}}
{{ .Summary }}
<p><i>(<a href="{{ .RelPermalink }}">Read More</a>)</i></p>
{{ else }}
{{ .Content | safeHTML }}
{{- end -}}
{{- if .Params.linkurl -}}
<p><a href="{{ .RelPermalink }}"><i class="fas fa-level-down-alt fa-xs"></i>&ensp;Permalink</a></p>
{{- end -}}

and setting the summary limit to infinite.

What this does is:

  1. If Hugo thinks that the post is .Truncated, return its summary. This means that the POST IS TRUNCATED ONLY IF I MANUALLY ADD THE MORE TAG, because the auto-summary limit is set to a big number.
  2. If hugo doesn’t think so (= no more tag explicitly added by me), then return the usual content. I didn’t change that part at all and the safeHTML is prolly not needed there but whatever.
Nel mezzo del deserto posso dire tutto quello che voglio.