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


I use [Obsidian](https://obsidian.md) 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](https://11ty.dev) 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
---
---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`:

```js
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](https://github.com/11ty/eleventy/discussions/2241)). 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.