Skip to content

Instantly share code, notes, and snippets.

@sebastien-attia
Last active January 8, 2021 11:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastien-attia/15df6e76a84ea5100c3b9b1a195d7540 to your computer and use it in GitHub Desktop.
Save sebastien-attia/15df6e76a84ea5100c3b9b1a195d7540 to your computer and use it in GitHub Desktop.
VueJS c omponent transforming Markdown and LateX in HTML

The MarkdownMathJax's VueJS component transforms a Markdown and LateX string into HTML.

It uses markdown-it and MathJax.

The following piece of code supposes that:

  • it runs in a nuxt project with the following nuxt.config.js config:
modules: [
  '@nuxtjs/markdownit'
 ],
// [optional] markdownit options
markdownit: {
  injected: true,
  preset: 'default',
  linkify: true,
  html: true,
  breaks: false,
  use: [
    // 'markdown-it-mathjax',
    'markdown-it-container',
    'markdown-it-attrs'
  ]
},
  • it uses MathJax to render LateX in HTML.

--- MarkdownMathJax.vue ---

<template>
  <span ref="mathJaxEl" v-html="readMD()" class="e-mathjax"></span>
</template>

<script>
export default {
  props: [ 'mdData' ],

  methods: {
    readMD () {
      return this.$md.render(this.mdData) 
    },

    renderMathJax () {
      if(window.MathJax) {
        window.MathJax.Hub.Config({
          tex2jax: {
            inlineMath: [ ['$','$'], ["\(","\)"] ],
            displayMath: [ ['$$','$$'], ["\[","\]"] ],
            processEscapes: true,
            processEnvironments: true
          },
          // Center justify equations in code and markdown cells. Elsewhere
          // we use CSS to left justify single line equations in code cells.
          displayAlign: 'center',
          "HTML-CSS": {
            styles: {'.MathJax_Display': {"margin": 0}},
            linebreaks: { automatic: true }
          }
        });
        window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub,this.$refs.mathJaxEl]);
      }
    }
  },

  head: {
    script: [
      { src: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML' }
    ]
  },

  mounted () {
    this.renderMathJax()
  }
}
</script>

--- End of MarkdownMathJax.vue ---

@DasarathanSampath
Copy link

This really works and thanks for documenting this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment