Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Markdown content split to sections in Eleventy and Nunjucks

Code in this blog post was written with versions: eleventy: 3.1.2, Nunjucks: 3.2.4

Last night, while sitting in the train on my way home, I got nerdsniped into writing another Eleventy post by tlohde who asked if there was a way to separate content from a Markdown post so it could be used in multiple parts in the layout. You can read the full question in the toot linked earlier.

I couldn’t resist figuring the puzzle out. Before I had my solution tested, Mark Llobrera shared his approach with shortcodes but I wanted to offer an alternative with Filters.

Let’s start with the filter. In your Eleventy config, add:

eleventyConfig.addNunjucksFilter("split_by_keyword", (body, index) => {
  return body.split("=~=~=~=")[index];
});

Here, I decided to use =~=~=~= as the splitting keyword as that is a beautiful section marker in Markdown but you can use whatever you like.

In your layout (let’s call it layouts/two-parter.njk), you can then do:

<body>
  {{ content | split_by_keyword(0) | safe }}
  <h2>Second part</h2>
  {{ content | split_by_keyword(1) | safe }}
</body>

Here, I’m splitting into two. If you sometimes have a need for a three-section layout, create a new layout and add another call to content with the filter. The same filter works with as many sections as you like but the amount of section splits in the layout needs to match the amount of splitting keywords in your content or otherwise some parts will be left out.

Finally, to use this layout with your Markdown file, you can do

---
layout: layouts/two-parter.njk
---


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus et
ultricies diam. Vivamus sodales felis sed neque pellentesque, ut
elementum orci laoreet. Quisque lorem est, tempor in lectus sodales,
bibendum faucibus elit.

=~=~=~=

Sed iaculis ligula in volutpat feugiat. Nam eu lacus rhoncus, gravida
eros eget, aliquet mauris. Fusce sit amet convallis purus. Nam sagittis
sit amet ex id sagittis. Nullam mattis urna ut dapibus aliquam. In
imperdiet vitae elit vitae faucibus.

and it will render with the first paragraph, then a h2 from the layout and then the second paragraph.


If something above resonated with you, let's start a discussion about it! Email me at juhamattisantala at gmail dot com and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.