Using LaTeX with Pelican
As a passionate blogger of many years I've increasingly had a desire to formalize ideas I'm working on using mathematics. After all, as I always say, "Math is truth". That said, it's hard to express mathematical notation in digital media. Or rather I should say it's hard if you can't use LaTeX : ) .
So when I recently upgraded my blogging system (now using pelican) one of the first things I had to figure out was how to support LaTeX. A little research turned up (as always) not just one but multiple approaches ranging from modding templates to using a number of plugins. After thinking about the alternatives, it turns out that the simplest, downest, dirtiest approach (for me) was to add a simple script to my theme. The approach is quick, easy, least touch and robust.
Method
The method uses MathJax. MathJax is a javascript display engine for mathematics that just plain works in all browsers. To use it simply:
- include the following script in you HTML header element for your page template:
<script type="text/javascript" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
- Add the following script in the same area:
<script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] } }; </script>
And bang! you're done. Easy peasy.
Following I have a few tests that show how easy it is to use LaTeX with these changes...
-
Same line rendering: $\color{red}{f(x) = x^2}$ . The math should render in-lined.
-
Same line rendering: $f(x) = x^2$ . The math should render in-lined.
-
TEST: if I had $1,000,000.00, I would buy you a house... (you should see the dollar character '\$')
-
Block Rendering. Remember the activation function?
$$ \sigma \left( \sum a_i w_{ij} + b_j \right) $$
Update
Ran into an issue with latex rendering using alignment. Often I need to align around the equal sign as in:
$$ \begin{align} P ( Hyp | Event ) &= \frac {P ( Event | Hyp ) \times P ( Hyp ) } { P ( Event ) } \\ &= \frac {0.99 \times 0.25 } { 0.50 } \\ &= 0.495 \end{align} $$
'Problem is, in such cases Pelican will perform entity substitution on the the '&' (i.e., '&' --> &) causing the alignment to fail. To work around the issue, wrap the latex in a div like so...
<div> $$ \begin{align} P ( Hyp | Event ) &= \frac {P ( Event | Hyp ) \times P ( Hyp ) } { P ( Event ) } \\ &= \frac {0.99 \times 0.25 } { 0.50 } \\ &= 0.495 \end{align} $$ </div>
Resources
- MathJax .