Change your colour scheme

Detecting Markdown titles with Eleventy


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.

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/detecting-markdown-titles-with-eleventy), 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.


About the author

My face

I'm Lewis Dale, a software engineer and web developer based in the UK. I write about writing software, silly projects, and cycling. A lot of cycling. Too much, maybe.