lewisdale.dev/src/blog/posts/2024/1/detecting-markdown-titles-eleventy.md
Lewis Dale 8d2c1da6f1
All checks were successful
Build and copy to prod / build-and-copy (push) Successful in 1m53s
Add explicit dates to posts
2024-03-08 07:14:42 +00:00

2.2 KiB

title tags date
Detecting Markdown titles with Eleventy
Eleventy
Obsidian
2024-01-10T08:44:57Z

I use Obsidian for note-taking, and I'd love to publish those notes somewhere I can easily browse them, personal-wiki style, and ideally I'd want to use Eleventy to do it.

The main blocker is that Obsidian uses file slug/Markdown titles, whereas Eleventy requires the title to be set in frontmatter. Obsidian supports adding frontmatter, but it feels weird to have the title set in 2 different places. So here's a quick solution that parses titles out of the document body, and then uses it as the entry title.

---
---js
{
    eleventyComputed: {
        title: data => {
            const fs = require('fs');
            const content = fs.readFileSync(data.page.inputPath, 'utf-8');
            const withoutFrontMatter = content.replace(/^---[^]*---/, '');
            const title = withoutFrontMatter.match(/#{1}\s(.+)/);
            return title ? title[1] : 'No title detected :sad:';
        }
    }
}
---

This is using Javascript frontmatter, using the eleventyComputed.title key, we first:

  1. Get the contents of the current file, because it's not included in the data passed to the function
  2. Strip out the frontmatter using regex
  3. Match the first instance of a string that looks like a Markdown heading
  4. If it exists, return it.

This works, but it broke the permalink logic (I was using permalink: "/post/{{ title | slugify }}), because the computed values won't have been available at that point. So, I just have to move my permalink into eleventyComputed:

permalink: function(data) {
    const title = data.slug ?? data.title;
    return `/post/${this.slugify(title)}/`
}

It works pretty well! There are some obvious flaws, and probably some better approaches. As I've already mentioned, Obsidian uses the Markdown heading for file slugs, so that's also an option (and is discussed in this Github discussion). Also reading in the entire file to get the title is probably not ideal from a performance perspective.

But, it was early in the morning and nobody was around to stop me.