{{page.excerpt}} does not work if first element is not <p>

As the title says, if I’m using {{ page.excerpt | strip_html | normalize_whitespace | truncate: 160 | escape }} to generate meta descriptions. However, if a posts begins with an image or anything other than <p> it simply returns " ".

Also, it seems this only picks up whatever is in the first <p> it finds, so even if the words within the first <p> are less than 160 characters, it still only displays that content.

Is there a way around this?

From https://jekyllrb.com/docs/posts/#post-excerpts :

Each post automatically takes the first block of text, from the beginning of the content to the first occurrence of excerpt_separator, and sets it as the post.excerpt.

So, I suppose that after your image there is a excerpt_separator, and then it stops there. Maybe it works if you define your own excerpt_separator, maybe a </p> ?

You can also override the autogenerated excerpt by setting page.excerpt yourself in the YAML Front Matter.

title: Your Post
excerpt: Your custom excerpt.

Thank you. However, I am using this as a fallback for when a post does not have a description.

Makes sense. I guess I just assumed jekyll would scan the post’s content until it found the first paragraph and take the excerpt form there, regardless of whether the first element is an image or not. Could this be a bug?

I don’t think it’s a bug. The way Kramdown parses an image eg. ![your image](image.jpg) is to wrap it in a paragraph.

So Jekyll’s auto-generating excerpt feature is doing the write thing and grabbing it.

I think your best bet is to use an excerpt separator as @lsrdg mentioned above.

Drop in excerpt_separator: <!--more--> in your post’s front matter, then manually insert <!--more--> after whatever text you want Jekyll to consider as the excerpt.

You could also try wrapping your image Markdown in div or figure element. I believe that will stop Kramdown from wrapping it with <p></p>.

<div>![your image](image.jpg)</div>

Thanks. They actually are wrapped using figure tags. I think the problem nay actually stem from the fact that I am using Json-ld to add schema data, so the script is the first thing that Kramdown sees. Not sure moving it below the image will make a difference, so I’ll have to look into using an excerpt separator.

BTW, big fan of your work; your blog has been an invaluable resource for learning.

1 Like