How to Write Math in Kirby CMS

March 16th, 2017

In my second blog article, I wrote about the decision to choose Kirby CMS as a blogging platform. Kirby was perfectly up to my expectations until I started writing my last article, Modeling a Natural Language. This article involved couple of mathematical symbols and equations. It turned out Kirby's default Markdown module does not support math symbols and equations.

Since I wanted to get the article out as soon as possible, therefore as a quick solution I decided to generate images of math equations and inserted them in the text. However, that was not an ideal solution because generating images was frustratingly time consuming. In case of a tiny mistake I had to do the whole thing again. In addition to that I could not write in-line math equations or symbols.

Consequently, for next math driven articles I set out to look for a reliable long term solution which would allow me to write math equations in Kirby editor. Kirby has quite a few nice plugins to upgrade and customize your CMS. Unfortunately, it does not have any plugin to incorporate math feature. Therefore, I had to implement this feature myself through custom Kirbytag. The custom math tag (named as mymath) allows to write almost any Latex style math equation or symbol, for instance, (mymath: x=\frac{1+y}{1+2z^2}) will get rendered in-line as $x=\frac{1+y}{1+2z^2}$

The mymath tag relies on MathJax, an open source JavaScript platform for display of mathematics. The tag implementation is very simple and can be done in 2 steps;

1. Installing MathJax

  • Go to MathJax website and download latest version of MathJax.
  • Unpack MathJax directory and move it inside Kirby directory
  • include MathJax by add following line to 'head' html tag (of header snippet at site/snippets/header.php);
<script type="text/javascript" src="<?php echo url() ?>/MathJax270/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

2. Create Custom Kirbytag, mymath

  • create a new file 'kirby_directory_path/site/tags/mymath.php'
  • add following code to 'mymath.php'
<?php
kirbytext::$tags['mymath'] = array(
    'attr' => array(
    'style'
  ),
  'html' => function($tag) {

    $math_value = $tag->attr('mymath');
    $style_value    = $tag->attr('style', 'inline');
    $style_tag = '$'; // 'inline' by default

    if (strcmp($style_value, 'display') == 0) {
        $style_tag = '$$';
    }

    return $style_tag .  $math_value. $style_tag;
  }
);

The mymath tag has two attributes: 1) equation/symbol itself and 2) style [default: in-line]. The optional style attribute tells whether equation should be rendered in-line or as block. The default style is in-line i.e. if you do not provide value of style attribute, the equation will be displayed in-line.

Examples:

(mymath: x=1+2z^2) renders in-line (default) $x=1+2z^2$

whereas (mymath: x=1+2z^2 style: display) renders as a block on new line $$x=1+2z^2$$