.md support[.md]

I came across a blog last year from another technologist (I'm afraid I can't remember which one), and they had a really neat feature where appending .md to the URL would render the markdown version of the current page. I ventured to do the same.

This website is a static site which is generated from a very minimal build system I wrote, and just about every page is generated from a markdown source file. So, this functionality should actually be fairly easy to retrofit.

Turns out all I need to do was the following:

config.js

  const targets = [
    // ...
    (data) => {
      return data.pages.map((page) => {
        return [
          {
            template: 'page.njk',
            dest: `dist/${page.fields.url}/index.html`,
            include: ['pages'],
            extraContext: {
              ...page.fields
            }
          },
+         
+         // .md version for blog posts
+         ...(page.fields.blogPost ? [
+           {
+             template: 'markdown.njk',
+             dest: `dist/${page.fields.url}.md`,
+             include: ['pages'],
+             extraContext: {
+               ...page.fields
+             }
+           }
+         ] : [])
        ];
      });
    }
  ];

src/markdown.njk

+ {% filter unescape -%}
+ # {{ title }}
+ 
+ {% if date -%}
+   {{ date }}
+ {%- endif %}
+ 
+ {% if hero -%}
+   ![image]({{ hero.fields.file.url }})
+ {%- endif %}
+ 
+ {{ content }}
+ {%- endfilter %}

lib/nunjucks.js

+ import { decode } from 'html-entities';

+ env.addFilter('unescape', (str) => {
+  return env.filters.safe(decode(str));
+ });

And — tada! — here's the Markdown version of this page: /md-support.md


Comments