Render TeX in Hugo Blog
Recently, I started to think about learning $\TeX$, adding $\TeX$ support to blog looks like a good start for me. It took me quite some time to figure out all the culprits of embedding $\TeX$ in markdown. I hope this blog could save you some time before starting writing in $\TeX$.
Note: Some contents in this post is outdated. Hugo markdown engine moved from Blackfriday to Goldmark.
Required Components
- The default Blackfriday markdown engine.
- $\KaTeX$ math typesetting library for the web.
Steps to Setup $\KaTeX$ in Hugo
$\KaTeX$ is an excellent fast engineer for rendering $\TeX$ on web. The $\KaTeX$ Auto-render Extension is an extension to automatically render all of the math inside of text.
Example:
Code:
|
|
Integrate $\KaTeX$ Auto-render Extension
The first step is to find the right place to include the $\KaTeX$ Auto-render Extension. It is different by theme, usually, the header.html
or footer.html
could be the ideal place; or, if the theme support math libraries, it may provide a separate HTML, in my case, it is math.html
.
Locate the HTML file, create the same directory structure in your project, copy the HTML, and include the library. Here is my math.html
, a new parameter katex
is defined in it.
|
|
Enable $\KaTeX$ in Markdown
Enable the parameter katex
in the posts which require $\TeX$. Depend on the markdown header format, it could be TOML or YAML.
- TOML
|
|
- YAML
|
|
Time to Dance
First, The Known Issues
Check the official document for Issues with Markdown and Solution.
-
The underscore character
_
It is interpreted by Markdown as a way to wrap text in
emph
blocks while it is a way to create a subscript in $\TeX$.- Escape each underscore in your math code by entering
\_
instead of_
. - Wrap the math expression inside a
<div>
</div>
block.
- Escape each underscore in your math code by entering
-
The newline
\\
Markdown engineer interprets
\\
as<br>
, it breaks the $\TeX$.- Use
\newline
instead of\\
. - Wrap the math expression inside a
<div>
</div>
block.
- Use
-
Escape slash character
\
- Escape the inline delimiter
\\(
and\\)
. - Another case I found is the slash in markdown title.
- Escape the inline delimiter
Inline Math
Use $
$
or \(
\)
as delimiters for inline math. It can also be used to align a block on left.
Example: Given an array of integers $A (a_i \geq 0, i \in [0, n])$
Code: Given an array of integers $A (a\_i \geq 0, i \in [0, n])$
Displayed Math
Use $$
$$
or \[
\]
as delimiters for inline math, and wrap the section by <div>
</div>
Example:
Code:
|
|