kerrickstaley / genanki

A Python 3 library for generating Anki decks
MIT License
2.06k stars 162 forks source link

HOWTO: insert script into template model? #40

Closed skewballfox closed 5 years ago

skewballfox commented 5 years ago

I'm trying to add mathjax support to one of my model templates using this guide

I have to insert it to the front and the back of the card, so far I tried to load it in

mathjax="<script type=\"text/x-mathjax-config\">\n"
mathjax+="MathJax.Hub.processSectionDelay = 0;\n"
mathjax+="MathJax.Hub.Config({\n"
mathjax+="  messageStyle: 'none',\n"
mathjax+="  showProcessingMessages: false,\n"
mathjax+="  tex2jax: {\n"
mathjax+="    inlineMath: [['$', '$']],\n"
mathjax+="    displayMath: [['$$', '$$']],\n"
mathjax+="    processEscapes: true\n"
mathjax+="  }\n"
mathjax+="});\n"
mathjax+="</script>\n"
mathjax+="<script type=\"text/javascript\">\n"
mathjax+="(function() {\n"
mathjax+="  if (window.MathJax != null) {\n"
mathjax+="    var card = document.querySelector('.card');\n"
mathjax+="    MathJax.Hub.Queue(['Typeset', MathJax.Hub, card]);\n"
mathjax+="    return;\n"
mathjax+="  }\n"
mathjax+="  var script = document.createElement('script');\n"
mathjax+="  script.type = 'text/javascript';\n"
mathjax+="  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML';\n"
mathjax+="  document.body.appendChild(script);\n"
mathjax+="})();\n"
mathjax+="</script>\n"
reversible_mathjax = genanki.Model(
1179517143,
'Reversible Model with mathjax',
fields=[
  {'name': 'Question'},
  {'name': 'Answer'},
],
templates=[
  {
    'name': 'Card 1',
    'qfmt': ('{{Question}}\n{}').format(mathjax),
    'afmt': ('{{FrontSide}}<hr id="answer">\n{}').format(mathjax),
  },
  {
    'name': 'Card 2',
    'qfmt': ('{{Answer}}\n{}').format(mathjax),
    'afmt': ('{{FrontSide}}<hr id="answer">{{Question}}\n{}').format(mathjax),
  }
])

Turns out this worked, but I still want to leave this here for other people to use.

skewballfox commented 5 years ago

okay so this didn't work, but it may be related to anki rather than the script, I'm going to try to get this working over the next few days.

kerrickstaley commented 5 years ago

In general, when trying to get things like this to work, try doing it inside Anki first and then convert what you have into a genanki program.