Original post is here: eklausmeier.goip.de
This blog runs using Simplified Saaze. Almost every blog post contains categories and tags. Although previously these categories and tags were not linked together in any way. I.e., there is no way to find all blog post relating to one specific category.
Task at hand: Add categories and tags to Simplified Saaze.
When I imported my content from WordPress I also imported categories and tags. Though, they were just shown at the bottom of each post. There was no connection between different post having the same category or tag.
It turns out that categories and tags can be added to Simplified Saaze without changing a single line in Saaze. It is sufficient to add a simple Perl script and change templates.
1. Overview. The overall architecture is as given below. [mermaid] flowchart LR subgraph MAIN direction TB A[php saaze] --> B["TemplateManager::renderEntry()"] B --> C[category.php] C --> D[[index.html]] B --> E[tag.php] E --> F[[index.html]] end subgraph Perl direction LR G["blogcategory *.md"] --> H[[cat_and_tag.json]] end Perl --> MAIN [/mermaid] A separate program generates a JSON file with categories and tags. This file is then picked up by the template PHP code. The JSON file holds information for categories and tags in one single file. The JSON looks something like this:
1{
2 "categories": {
3 "Android": [
4 "<a href=\"../../blog/2013/03-13-screenshots-on-nexus-4-android-4-x\">2013-03-13: Screenshots on Nexus 4 (Android 4.x)</a>",
5 "<a href=\"../../blog/2013/08-04-google-now-emergency-alert\">2013-08-04: Google Now Emergency Alert</a>",
6 ...
7 "tags": {
8 "/etc/shells": [
9 "<a href=\"../../blog/2015/10-05-linux-pam-and-etcshells\">2015-10-05: Linux pam and /etc/shells</a>"
10 ],
11 "2GB": [
12 "<a href=\"../../blog/2014/07-05-splitting-large-files-on-microsoft-windows\">2014-07-05: Splitting Large Files on Microsoft Windows</a>"
13 ],
14 ...
15}
This JSON file needs to be regenerated whenever new categories or tags show up. For example, when a new blog-post is written, or a previous post is changed in the frontmatter. In all other cases this JSON file stays untouched. It is similar to the way indexes are used in TeX or LaTeX.
2. Generate JSON file. Generating the JSON file from the frontmatter information in every Markdown file can be done by any program. I chose to write it in 50 lines of Perl. The script expects each Markdown file including directory as argument. Then the frontmatter in each Markdown file is parsed for date
, title
, categories
, and tags
. With these values it can then populate two hashes, called %cat
and %tag
. Key of each hash is either category or tag. Each value is an array. Each arry element is an URL pointing to the file where originated.
Finally the two hashes are printed out in JSON format.
1#!/bin/perl -W
2# Read frontmatter of Markdown file and write categories and tags to single JSON file
3# Call like this:
4# blogcategory `find blog -name \*.md` > cat_and_tag.json
5#
6# Elmar Klausmeier, 22-Mar-2022: listSplit(), readMkd()
7# Elmar Klausmeier, 01-Apr-2022: date, @ARGV, references in listSplit()
8# Elmar Klausmeier, 02-Apr-2022: write JSON
9# Elmar Klausmeier, 03-Apr-2022: JSON now in sub prtInnerJSON for both cat's & tags
10
11
12use strict;
13my (%cat, %tag); # each is hash of array of strings
14
15sub listSplit(@) {
16 my $s = $_[0];
17 $s =~ s/^\s*\[\s*"//; # strip ["
18 $s =~ s/"\s*\]//; # strip "]
19 return split(/",\s*"/,$s);
20}
21
22
23sub readMkd(@) { # read Markdown file and put categories and tags in hashes
24 my $fname = $_[0];
25 #printf("fname=%s\n",$fname);
26 open(F,"<$fname") || die("Cannot open $fname");
27 my ($threedash,$draft,$title,$date,@catArr,@tagArr) = (0,0,"","",(),());
28 while (<F>) {
29 chomp;
30 s/\s+$//; # rtrim
31 if (/^\-\-\-\s*$/) { last if (++$threedash >= 2); }
32 elsif (/^title:/) { $title = substr($_,6); $title =~ s/^\s*"//; $title =~ s/"$//; }
33 elsif (/^date:/) { $date = substr($_,5); $date =~ s/^\s*"//; $date = substr($date,0,10); }
34 elsif (/^draft:\s*true/) { $draft = 1; last; }
35 elsif (/^categories:/) { @catArr = listSplit(substr($_,11)); }
36 elsif (/^tags:/) { @tagArr = listSplit(substr($_,5)); }
37 }
38 close(F) || die("Cannot close $fname");
39 return if ($draft == 1);
40 $fname =~ s/\.md$//;
41 my $url = "<a href=\\\"../../$fname\\\">$date: $title</a>";
42 foreach (@catArr) { push $cat{$_}->@*, $url; }
43 foreach (@tagArr) { push $tag{$_}->@*, $url; }
44}
45
46
47sub prtInnerJSON(@) {
48 my $href = $_[0]; # hash reference
49 my $n = keys %{$href}; # for comma at end of list
50 foreach my $key (sort keys %{$href}) {
51 print "\t\t\"$key\": [\n";
52 my $m = scalar @{%{$href}{$key}}; # for comma at end of list
53 foreach (sort @{%{$href}{$key}}) {
54 printf("\t\t\t\"%s\"%s\n", $_, --$m ? "," : "");
55 }
56 printf("\t\t]%s\n", --$n ? "," : "");
57 }
58}
59
60
61while (<@ARGV>) {
62 readMkd($_);
63}
64
65# Write the two hashes in JSON format
66print "{\n\t\"categories\": {\n";
67prtInnerJSON(\%cat);
68print "\t},\n\t\"tags\": {\n";
69prtInnerJSON(\%tag);
70print "\t}\n}\n";
Running above Perl script blogcategory
in my content directory on ca. 400 blog posts takes 30ms on an Intel i5-4250U, clocking 2.6 GHz.
1$ time blogcategory `find . -name \*.md` > cat_and_tag.json
2 real 0.03s
3 user 0.03s
4 sys 0
5 swapped 0
6 total space 0
3. Templates. In Simplified Saaze template files are just ordinary PHP files. The template categories.php
for categories is as below. Here we use a feature in Saaze and Simplified Saaze: Every Markdown file can have its own template file, i.e., with the template
keyword in the frontmatter one can specify which template to use. If no template
keyword is found then entry
is used for blog posts, and index
is used for index-pages.
The PHP code require
's a routine to read the JSON file. Then it simply prints the content of the JSON in table and/or list-form using prtCatOrTag()
.
1<?php require SAAZE_PATH . "/templates/top-layout.php"; ?>
2<?php require SAAZE_PATH . "/content/read_cattag_json.php"; ?>
3
4 <div class=blogarea>
5<p class=dimmedColor><?= date('jS F Y', strtotime($entry['date'])) ?></p>
6<h1><?= $entry['title'] ?></h1>
7
8<div>
9<?php prtCatOrTag($GLOBALS['cat_and_tag']['categories']); ?>
10</div>
11 </div>
12
13<?php require SAAZE_PATH . "/templates/bottom-layout.php"; ?>
The PHP file to read JSON, read_cattag_json.php
, is as below. It is 40 lines of PHP. It just reads the JSON file with file_get_contents()
then feeds the string to json_decode()
.
1<?php
2// read JSON file and store it in GLOBALS
3if (!array_key_exists('cat_and_tag',$GLOBALS)) {
4 $cat_and_tag_json = @file_get_contents(SAAZE_PATH . "/content/cat_and_tag.json");
5 if ($cat_and_tag_json === false)
6 exit(81);
7 if (($GLOBALS['cat_and_tag'] = json_decode($cat_and_tag_json,true)) === null)
8 exit(82);
9
10
11 function prtCatOrTag(array $hash) { // hash contains either categories or tags
12 ...
13 }
14}
15?>
Added 13-Aug-2022: Simplified Saaze now has a new command-line argument -t
added, which generates the cat_and_tag.json
on the fly. So above Perl program is still valid, but no longer required.