Issues rendering LATEX with MathJax

Hello all! I’m very much a newbie, trying to create a small quiz app for studying data science topics. I’m having some trouble getting the MathJax equations to render properly.

I’ve checked the other questions about rendering LATEX and attempted to implement them but there are still some parts that aren’t rendering properly. For example, using the $$ notation for non-inline (outline?) math isn’t working. When I hit the “SUBMIT” button to check the user’s answer all of the MathJax text which was previously rendered properly (all inline) breaks, showing the raw strings.

The quiz is a custom component with the “form_show” function below included in its “show” event.

Example HTML to Render

<p>You are given the following four pairs of observations:
$$x_1=(-1,0), x_2=(1,1), x_3=(2,-1),\text{ and } x_4=(5,10).$$
A hierarchical clustering algorithm is used with complete linkage and Euclidean distance.</p>

<p>Calculate the intercluster dissimilarity between $\\{x_1,x_2\\}$ and $\\{x_4\\}$.</p>

Native Libraries Contents:

<script>
  MathJax = {
    tex: {
      inlineMath: [['$', '$'], ['\\(', '\\)']]
    }
  };
</script>
<script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

Relevant Python Code:

from anvil.js.window import MathJax
...
def form_show(self, **event_args):
    MathJax.typeset()
    pass

If y’all have any advice I’d greatly appreciate it! I’ve added a copy of the app below as well if anyone is willing to take the time to take a quick look.

Clone link:
[share a copy of your app] Anvil | Login

The Rich Text component has a restricted set of HTML it supports. It looks like that isn’t playing well with MathJax.

If the content is provided by you (and not by other users of your app), then you don’t need the protection that the restricted HTML provides. Instead you can use an instance of HtmlTemplate. That will take any HTML you give it, no restrictions.

For example:

    self.html_template = HtmlTemplate(html=self.questions[self.curr_num]['question-text'])
    self.add_component(self.html_template)

Put that at the end of your QuizContainer’s __init__ method and you’ll see the properly rendered MathJax in the component at the bottom of the form.

Since HtmlTemplate is not a component you can drag over, but must create in code, you’d normally put a flow panel where you want the template to be on your form, and use add_component on the flow panel to put the HtmlTemplate into it.

Do note that if the content is provided by other users, you do not want to use HtmlTemplate since that opens you up to XSS and XSRF sorts of exploits.

3 Likes

This worked perfectly, thank you so much!

1 Like