Restrict first paragraph of a post at build time

I would like to ensure that the first paragraph of any post in a given section of my website is restricted according to a function I define (that applies, say, to the unrendered or rendered content, I can work with either).

A simple example of this would be: ensure the first paragraph of the main body of any post is < 300 characters in length, or else the hugo build should fail.

I’m wondering what’s the most idiomatic way to support this. Can I define a build step that calls an arbitrary executable and checks for its exit code, and use that to hook into an arbitrary python script? Should I try to implement this using a custom template or shortcode and, so long as my condition can be expressed with the templating language, somehow raise an error from the template if the condition is not met?

Hugo’s security model prohibits you from executing arbitrary code, and that’s a very good thing.

The idiomatic approach is to use a regex to capture the content of the first rendered paragraph. Place something like this in the single.html template used to render the section in question:

{{ $maxLength := 299 }}
{{ $firstParagraph := index (index (strings.FindRESubmatch `<p.*?>(.*?)</p>` .Content 1) 0) 1 }}
{{ if gt (len $firstParagraph) $maxLength }}
  {{ errorf "The length of the first paragraph exceeds %d characters" $maxLength }}
{{ end }}

Note that the above does exactly what you said… it examines the first paragraph. If your page begins with something else (e.g., a table followed by a paragraph), the table content is excluded from the comparison.

3 Likes

Thank you for that solution!

In case anyone else stumbles on this, I enhanced it slightly to account for line breaks in the .Content

{{ $maxLength := 299 }}
{{ $collapsed := (strings.Replace .Content "\n" " ")}}
{{ $firstParagraph := index (index (strings.FindRESubmatch `<p.*?>(.*?)</p>` $collapsed 1) 0) 1}}
{{ if gt (len $firstParagraph) $maxLength }}
  {{ errorf "The length of the first paragraph exceeds %d characters" $maxLength }}
{{ end }}

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