Skip to content

Instantly share code, notes, and snippets.

@vmx
Last active July 10, 2020 14:32
Show Gist options
  • Select an option

  • Save vmx/280e6c9b3d740c7e8fedbf2048171f2f to your computer and use it in GitHub Desktop.

Select an option

Save vmx/280e6c9b3d740c7e8fedbf2048171f2f to your computer and use it in GitHub Desktop.
Rendering Markdown with embedded Mathematics
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Render Markdown file that contains Mathematics</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/markdown-it@11.0.0/dist/markdown-it.min.js" integrity="sha256-3mv+NUxFuBg26MtcnuN2X37WUxuGunWCCiG2YCSBjNc=" crossorigin="anonymous"></script>
<style>
.katex-display {
margin: 0;
}
.katex-display > .katex {
text-align: left;
}
</style>
</head>
<body>
<script>
const getMarkdown = async (url) => {
const response = await fetch(url)
const data = await response.text()
// Strip meta information header if there is one
return data.replace(/^---[\s\S]+?---/, '')
}
// Make sure the page reloads if you enter another Markdown file that
// should be loaded
window.onhashchange = () => { window.location.reload() };
const url = window.location.hash.substr(1)
if (url === '') {
document.body.innerHTML = `<p>
Missing URL after the hash.
Example: <code>${window.location}#https://example.org/file.md</code>
</p>`
} else {
getMarkdown(url).then((markdown) => {
const md = window.markdownit();
const html = md.render(markdown);
document.body.innerHTML = html
window.renderMathInElement(document.body, {
throwOnError: false,
// parse <code> and <pre> which are excluded by default
ignoredTags: ["script", "noscript", "style", "textarea"],
delimiters: [
{left: "$$", right: "$$", display: true},
{left: "$", right: "$", display: false},
]
})
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment