Article previews: based on line count, similar to truncate based on character count

I’m trying to truncate/limit my blog posts to a preview, and do so by line count. The aim is to have the front matter as follows:

[params]
  preview = true
  preview_lines = 7

And then following that, the layout would have code that would conditionally show only 7 lines of content if that preview is set to true.

I’ve come up with code that seems to do most of what I need, but the issue is that it keeps spitting out all markdown lines, but skips over anything wrapped in html code, including simple <p>s or <span>s

Here’s the code I have so far. I’ve played around with options with markdownify, but that ends up hiding all lines entirely. Thanks for your help!

{{ if .Params.preview }}
  {{ $content := .Content }}
  {{ $lines := default 7 .Params.preview_lines }}
  {{ $splitContent := split $content "\n" }}
  
  {{ if gt (len $splitContent) $lines }}
    {{ $truncated := delimit (first $lines $splitContent) "\n" }}
    {{ $truncated | safeHTML }}
    <span>...</span>
  {{ else }}
    {{ $content | safeHTML }}
  {{ end }}
{{ else }}
  {{ .Content | safeHTML }}
{{ end }}

mmh, keep in mind, that you operate on the already rendered HTML and you might get invalid HTML when you break up hard at a line break.

nevertheless with that setup I cannot reproduce your issue:

so it must be somewhere around in your template configuration, setup

toggle preview to se the effects

  • index.md

    ---
    Title: Home
    Params:
       preview: true
       preview_lines: 2
    ---
    
    1
    
    ## manual line based summary
    
    4
    
  • layouts/index.html

    {{ define "main" }}
      {{/* YOUR CODE /*}}
    {{ end }}
    
  • result is:

    <p>1</p>
    <h2 id="manual-line-based-summary">manual line based summary</h2>
    <span>...</span>
    

try it out with this source and check the HTML

---
Title: Home
Params:
   preview: true
   preview_lines: 3
---

1

## manual line based summary

-  list
   -  item
1 Like

I saw this disappeared but it’s back. Really appreciate the help! Made a big difference for my site. Thanks @irkode