How: latex > python > django-rest > js mathjax > html

hello there!

I’m trying to make a interactive engineering mechanics book using django and sphinx. I have set up an api which triggers the generation of some formulas in latex code.

For example:

\begin{table}
\caption{Point loads}
\label{F-loads}
\begin{tabular}{|c|c|c|}
\toprule
\midrule
$F_{x0}$ & {:0,2f} & N \\
$F_{y0}$ & {:0,2f} & N \\
\bottomrule
\end{tabular}
\end{table}

now what I’m doing now is adding this (and other latex code) to a python dict.
which results in:

{'pointloads': '\\begin{table}\n\\caption{Point loads}\n\\label{F-loads}\n\\begin{tabular}{|c|c|c|}\n\\toprule\n\\midrule\n$F_{x0}$ & {:0,2f} & N \\\\\n$F_{y0}$ & {:0,2f} & N \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n'}

I do understand why all these backlashes and enter notations arise. But this is problematic since its not readable latex code for mathjax anymore.

now I send this from the back-end to the front end using django-rest:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import DatasetSerializer

from solver.model import solver_js

class DatasetAPIView(APIView):
    def post(self, request):
        serializer = DatasetSerializer(data=request.data)
        if serializer.is_valid():
            dataset = serializer.validated_data

            # Call a function to perform random alterations
            altered_dataset = alter_dataset(dataset)

            return Response(altered_dataset, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def alter_dataset(dataset):

    altered_dataset = solver_js.main(dataset)
    # if result dictionary has a key 'error', return the error message
    return altered_dataset

and then paste it ob my website using javascript:

function apicall () {
    const dataset = modelClicker;

    fetch('/api/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(dataset),
    })
      .then(response => response.json())
      .then(data => {
        if (data.message && data.message.error) {
            // An error occurred, display the error message
            alert(data.message.error);
          } else {
            // No error, display the regular message (if any)
            if (data.message.info !== null) {
                console.log('info:',data.message.info);
            }
            if (data.message.warning !== null) {
                console.log('warning:',data.message.warning);
            }
            // remove hidden container solutionCard
            // Select the element with the id "solutionCard"
            const solutionCard = document.getElementById('solutionCard');

            // Remove the 'hidden' attribute
            solutionCard.removeAttribute('hidden');

            console.log('data:',data);

            // Extract the altered dataset from the response
            const alteredDataset = data.sympy;

            // Update the "solutionBody" div with the altered dataset
            document.getElementById('solutionBody').textContent = JSON.stringify(alteredDataset, null, 2);
          }
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };

now after some django templating i’m currently just putting the code on my website as text:

{ "pointloads": "\\begin{table}\n\\caption{Point loads}\n\\label{F-loads}\n\\begin{tabular}{|c|c|c|}\n\\toprule\n\\midrule\n$F_{x0}$ & {:0,2f} & N \\\\\n$F_{y0}$ & {:0,2f} & N \\\\\n\\bottomrule\n\\end{tabular}\n\\end{table}\n" }

However what I would like to do is use mathjax to render the latex code on my web page for each key/value pair in the dict. Unfortunately because the code is ‘sanitized’ i’m left with a lot of unwanted backslashes (\) and enter signs (\n). My question is, what is a best practice to do such I thing ? I guess this kind of problem should be something that is very general when working with dictionaries. However I have problems wrapping my head around finding the correct approach to tackle this problem. I’ve tried looking in converting the latex to json rather than a python dict, which did not work. I’ve also tried to fiddle around with bleach and nh3 to find a solution but nothing seemed to be fitting.

I know this is not really a django question but since this is in the scope of my django project I’m hoping the people here might have the knowledge what I should do in this case. This seems to be a fairly common problem, so there has to be a best practice for this.

Thank you in advance.