blog/content/posts/20240309_pseudocode_in_hugo.md

99 lines
2.4 KiB
Markdown
Raw Normal View History

2024-03-10 11:11:07 +01:00
---
title: How to render pseudocode in Hugo with pseudocode.js
slug: pseudocodejs-hugo
pseudocode: true
date: 2024-03-09
---
To render pseudocode in Hugo, you can use the `pseudocode.js` library.
Here is what I did to make this working on my blog.
## Theme configuration
In your theme files, you will first need to add link to the library CDN.
```html
<!-- in themes/<theme>/layouts/partials/pseucodode.html -->
<script>
MathJax = {
tex: {
inlineMath: [['$','$'], ['\\(','\\)']],
displayMath: [['$$','$$'], ['\\[','\\]']],
processEscapes: true,
processEnvironments: true,
}
}
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-chtml-full.js"
integrity="sha256-kbAFUDxdHwlYv01zraGjvjNZayxKtdoiJ38bDTFJtaQ="
crossorigin="anonymous">
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pseudocode@latest/build/pseudocode.min.css">
<script src="https://cdn.jsdelivr.net/npm/pseudocode@latest/build/pseudocode.min.js"></script>
```
And render all element with `pseudocode` HTMl class.
```html
<!-- in themes/<theme>layouts/partials/pseudocode-render.html -->
<script>
let pseudocodeElements = document.getElementsByClassName("pseudocode");
for (let element of pseudocodeElements) {
pseudocode.renderElement(element);
}
</script>
```
```html
<!-- in themes/<theme>/layouts/_default/baseof.html -->
<head>
...
{{ if .Param "pseudocode" }}
{{ partialCached "pseudocode" . }}
{{ end }}
</head>
<body>
...
<main>
{{ block "main" . }}{{ end }}
{{ if .Param "pseudocode" }}
{{ partialCached "pseudocode-render" . }}
{{ end }}
<main>
</body>
```
## Writing
Then, in your Markdown article, add the following in your frontmatter:
```yaml
---
pseudocode: true
---
```
And write your pseudocode, using the `algorithmic` $\LaTeX$ syntax.
````markdown
<pre id="hello-world-code" class="pseudocode">
\begin{algorithmic}
\PRINT \texttt{'hello world'}
\end{algorithmic}
</pre>
````
Which willl be rendered as:
<pre id="hello-world-code" class="pseudocode">
\begin{algorithmic}
\PRINT \texttt{'hello world'}
\end{algorithmic}
</pre>
## References
- `pseudocode.js` <https://github.com/SaswatPadhi/pseudocode.js>
- Mathematics in Markdown (Hugo documentation) <https://gohugo.io/content-management/mathematics/>