Math equations with Eleventy using TeXZilla
Published Tags: English, Mathematics, MathML, LaTeX.
Assumed audience:
- people making HTML websites with Eleventy
- people who understand of LaTeX markup
- people who know how to install npm packages.
Installing TeXZilla and making a filter
Install TeXZilla using the command npm install texzilla.
Then use it in your config file (for example .eleventy.js):
const TeXZilla = require("texzilla");
module.exports = function (eleventyConfig) {
eleventyConfig.addFilter("math", (latex) => {
return TeXZilla.toMathMLString(latex, true, false, false);
});
.toMathMLString method is described TeXZilla's GitHub wiki page:
TeXZilla.toMathMLString = function(aTeX, aDisplay, aRTL, aThrowExceptionOnError)
aTexis the LaTeX equation and is given to the function aslatex.aDisplaydetermines if the MathML equation will be inline or a block element. Options aretrueorfalse.- Here I'm using
true, so every equation is a block element.
- Here I'm using
aRLTdetermines if the reading direction is from right o left. Options aretrueorfalse.- Here I'm using
false, so the reading direction is from left to right.
- Here I'm using
aThrowExceptionOnErrordetermines if the transformation fails, there would be an error message when transforming the LaTeX markup into MathML markup. Options aretrueorfalse.- I'm using
false, so I'm not getting any error messages.
- I'm using
Using the filter
Use the filter like any other (in Nunjucks) while using Eleventy.
First write the LaTeX equation that you want to see rendered in MathML. Then apply the following filters:
{{ "\\frac{1}{\\sqrt{2}}" | math | safe }}
Notice that you have to escape the slashes that LaTeX uses and that you need to also use the safe filter, so that the curly brackets aren't escaped (I assume, I'm not that sure - but it works!).
The end result
After all this we have a properly rendered MathML equation (assuming your browser supports it, nowadays the major ones should):
Continuation
This isn't the most straightforward or elegant solution, but it's a start I managed to do. Shout out to Eleventy Discord! People there really helped me out with this.
The best case scenario would be to just be able to write LaTeX markup and have it converted to MathML without individual filters.