Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

webbureaucrat
webbureaucrat

Posted on • Originally published atwebbureaucrat.gitlab.io on

     

How to Use Excerpts in Eleventy

Recently, I added first-paragraphpost excerpts tothis Eleventy blog's homepage post list. I found it wasn't as easy as I expected. It wasn't all documented all in one place. Further, in order to use Markdown excerpts in HTML, I had to write a simple custom filter. I'd like to document the process here from end to end.

Enablegrey-matter excerpts in.eleventy.js.

The first thing we need is to configure Eleventy to be able to see our excerpts. This is easily done by adding this line to the.eleventy.js configuration file into the mainmodule.exports = function(eleventyConfig) { ... } function.

eleventyConfig.setFrontMatterParsingOptions({excerpt:true});
Enter fullscreen modeExit fullscreen mode

Optional: Set the excerpt separator

The excerpt separator is some string which marks the end of the excerpt and the beginning of the rest of the article. By default, it is "---" but this default is easily overridden using the optionalexcerpt_separator property of the Front Matter parsing options object, like so:

eleventyConfig.setFrontMatterParsingOptions({excerpt:true,excerpt_separator:"--excerpt--"});
Enter fullscreen modeExit fullscreen mode

Add excerpt separators into each post

Now you can mark each post with excerpt separators. I use the default "---", but you can use whateverexcerpt_separator you may have overridden it within the previous step.

Write a simple custom filter to read Markdown excerpts

At this point, we need to reconcile a potential conflict. In my case at least,I am writing blog posts in markdown, but my post list on the homepage is a.njk that compiles to HTML. I don't want to change either of those things, but if I reference my markdown excerpts in HTML, they'll show up as raw markdown text. I need to write a bit of middleware to reconcile the two.

Start by locating your markdownIt options object. You'll find it in a block of code that looks something like this:

letmarkdownLibrary=markdownIt({html:true,breaks:false,linkify:true});eleventyConfig.setLibrary("md",markdownLibrary);
Enter fullscreen modeExit fullscreen mode

You'll need to reuse this object, so it's a good practice to separate it into its own constant at the top of the file...

constMARKDOWN_OPTIONS={html:true,breaks:false,linkify:true};
Enter fullscreen modeExit fullscreen mode

...that can be referenced in multiple places

letmarkdownLibrary=markdownIt(MARKDOWN_OPTIONS);eleventyConfig.setLibrary("md",markdownLibrary);
Enter fullscreen modeExit fullscreen mode

This is all in the service of writing a simple custom filters that can take markdown strings and turn them into HTML fragments. This will do it for us.

eleventyConfig.addFilter("toHTML",str=>{returnnewmarkdownIt(MARKDOWN_OPTIONS).renderInline(str);});
Enter fullscreen modeExit fullscreen mode

Use the custom filter to display the HTML excerpts in your post lists

Now, finally, I can include this excerpt in my/_includes/postlist.njk,which iterates over theposts collection like so:

(Fair warning: I formatted this for readability. If you copy/paste this, you may see some whitespace issues to fix.)

{% for post in postslist | reverse %}<liclass="postlist-item{% if post.url == url %} postlist-item-active{% endif %}"><h2class="h2-postlist"><ahref="{{ post.url | url }}"class="postlist-link">         {% if post.data.title %}          {{ post.data.title }}         {% else %}<code>{{ post.url }}</code>         {% endif %}</a></h2><timeclass="postlist-date"datetime="{{ post.date | htmlDateString }}">       {{ post.date | htmlDateString }}</time>     {% for tag in post.data.tags %}       {%- if collections.tagList.indexOf(tag) != -1 -%}         {% set tagUrl %}/tags/{{ tag }}/{% endset %}<ahref="{{ tagUrl | url }}"class="tag">{{ tag }}</a>       {%- endif -%}     {% endfor %}</li> {% endfor %}
Enter fullscreen modeExit fullscreen mode

Let us pipe the post excerpt into ourtoHTML custom filter and then pipe the output of our filter to the built-insafe filter so that Eleventy treats the output as HTML instead of plain text.

{% for post in postslist | reverse %}<liclass="postlist-item{% if post.url == url %} postlist-item-active{% endif %}"><h2class="h2-postlist"><ahref="{{ post.url | url }}"class="postlist-link">         {% if post.data.title %}          {{ post.data.title }}         {% else %}<code>{{ post.url }}</code>         {% endif %}</a></h2><timeclass="postlist-date"datetime="{{ post.date | htmlDateString }}">       {{ post.date | htmlDateString }}</time>     {% for tag in post.data.tags %}       {%- if collections.tagList.indexOf(tag) != -1 -%}         {% set tagUrl %}/tags/{{ tag }}/{% endset %}<ahref="{{ tagUrl | url }}"class="tag">{{ tag }}</a>       {%- endif -%}     {% endfor %}     {%- if post.data.page.excerpt -%}<p>{{ post.data.page.excerpt | toHTML | safe}}</p>     {%- endif -%}</li> {% endfor %}
Enter fullscreen modeExit fullscreen mode

And now when we runnpx eleventy --serve we should see our excerpts everyplace we reference_includes/postlist.njk.

Click here for a live demo.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

functional programming enthusiast and civic tech nerd.
  • Location
    Chicago, IL
  • Education
    Bachelor of Science, Computer Science, DePaul University
  • Work
    Software Developer
  • Joined

More fromwebbureaucrat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp