【Hugo】Support Latex Math Expressions

Posted by 西维蜀黍 on 2021-11-06, Last Modified on 2022-02-19
  1. Create a file in your theme directory layouts/partials/mathjax_support.html as the following:

      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']],
          displayMath: [['$$','$$'], ['\\[', '\\]']],
          processEscapes: true,
          processEnvironments: true
        options: {
          skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre']
      window.addEventListener('load', (event) => {
            x.parentElement.classList += 'has-jax'})
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script type="text/javascript" id="MathJax-script" async
  2. Next, open the file layouts/partials/header.html and add the following line just before the closing </head> tag:

    {{ if .Params.mathjax }}{{ partial "mathjax_support.html" . }}{{ end }}
  3. Then, add the following lines to your CSS file. You may need to tinker with the contents here depending on your theme, these are just the settings which worked for me.

    code.has-jax {
        -webkit-font-smoothing: antialiased;
        background: inherit !important;
        border: none !important;
        font-size: 100%;
  4. Finally, add mathjax: true to the YAML frontmatter of any pages containing math markup. Alternatively, you could omit the outer {{ if .Params.mathjax }} … {{ end }} conditional above to load the library automatically on all pages. However given that this library is quite heavy (it’s consistently the asset that Google PageSpeed Insights complains the most about) and that only <20% of my blog posts contain math at all, this is worth the extra effort for me.