I’m writing an addon that modifies the HTML content of {{sentence}} field by higlighting the {{vocab}} in it. I am trying to wrap vocab in a span tag but for some reason the HTML isn’t injected in the card.
init.py
from aqt import gui_hooks
from .highlighter import highlight_vocab
def on_add_note(note, _card):
if not note:
return
try:
vocab = note["vocab"]
sentence = note["sentence"]
highligted = highlight_vocab(vocab, sentence)
if highligted != sentence:
note["sentence"] = highligted
except Exception as e:
print(f"[Vocab highlighter] Error: {e}")
gui_hooks.add_cards_will_add_note.append(on_add_note)
highlighter.py
def highlight_vocab(vocab, sentence) :
vocab = vocab.strip()
sentence = sentence.strip()
if vocab and sentence :
if vocab in sentence:
return sentence.replace(vocab, f'<span class = "highlight">{vocab}</span>')
else:
return sentence
else:
return sentence
Have you tried using JS in the card template itself? Give the place you are modifying an id (wrapped in a span) and then add a highlight span to the vocab words.
Yes , Initially I was using javascript to do this but it was not working after researching a little I found out that javascript isn’t consistent in anki and breaks more often than not. So I decided to make an addon via python but somehow this is also not working
Does it? I use quite a bit of JS code in my own templates and it works fine across multiple devices and OSes.
I cannot help with addon development but maybe I could help with your template, if you provide your existing code and a summary of what you want to achieve.
(It would also be very weird if the JS code would break “more often than not”. Anki uses a real bundled browser to display all of it’s cards – if JS would break, then the entire browser it is build upon would be pretty much useless – and if I remember correctly, it uses the chromium browser, which is one of the post successful browsers in the world)