a blog about web development, authored by David Neustadt

aboutco.de

2019/04/18

About This Blog

So, for the first entry in this blog, I'm gonna write about, well, this blog!

A blog written in Markdown

I don't quite know what the target audience of this blog might be, so you may or may not know what markdown is. Very simply put, markdown is a simplified way of formatting text using plain text as its source.

All I wanted for this page was a light weight solution where I could quickly put up content, without the hassle of logging into a backend and fiddling about with a WYSIWYG editor.

What I came up with is a few lines of PHP, scanning a folder where I throw in Markdown files. Those end up being the very posts you are reading in this blog. Let's look at those few lines of code, shall we?

if (is_dir($dir)) {
    $files = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['.', '..']);
    $this->total = count($files);
    $files = array_slice($files, $offset, $length);

    foreach($files as $filename) {
        $contents[] = [
            'time' => DateTime::createFromFormat('Ymd', substr($filename, 0, 8)),
            'title' => ucwords(str_replace('_', ' ', substr($filename, 8, -3))),
            'content' => $this->parsedown->text(file_get_contents(join('/', [$dir, $filename]))),
        ];
    }
}

And at it's core, that is it. Sure, there is a little more to it, like the actual output of the content, the pagination of contents and stuff. But really what it comes down is:
I put .md files into a folder, naming them consistently by the pattern of the first 8 digits being in the format of Ymd DateTime and everything beyond that becoming the title of the post. Then there is the actual content of the post where we parse the previously mentioned markdown syntax and convert it to actual HTML. I'm using the excellent Parsedown package to do so.

The Caveats

Obviously, there are a few caveats to the described procedure. We are certainly wasting processing time parsing the markup of each post every time, not caching the resulting markup. But then again Parsedown is really fast parsing the markdown. I definitely wouldn't recommend doing so for a lot of content and/or highly frequented pages, but for the sake of convenience, it's really nice to quickly put up some content without having to deal with caching or other backend stuff.

You can find the whole code comprising this page here for reference.


Page 1