add hook to modify template prior to rendering

This commit is contained in:
Damien Elmes 2020-01-13 21:57:15 +10:00
parent e98327f10d
commit 33bf4c204b
3 changed files with 21 additions and 0 deletions

View file

@ -668,6 +668,10 @@ where c.nid = n.id and c.id in %s group by nid"""
hooks.run_modify_fields_for_rendering_hook(fields, model, data) hooks.run_modify_fields_for_rendering_hook(fields, model, data)
fields = runFilter("mungeFields", fields, model, data, self) # legacy fields = runFilter("mungeFields", fields, model, data, self) # legacy
# and the template prior to rendering
qfmt = hooks.run_original_card_template_filter(qfmt, True)
afmt = hooks.run_original_card_template_filter(qfmt, False)
# render fields # render fields
qatext = render_card(self, qfmt, afmt, fields, card_ord) qatext = render_card(self, qfmt, afmt, fields, card_ord)
ret: Dict[str, Any] = dict(q=qatext[0], a=qatext[1], id=card_id) ret: Dict[str, Any] = dict(q=qatext[0], a=qatext[1], id=card_id)

View file

@ -46,6 +46,7 @@ modify_fields_for_rendering_hook: List[
] = [] ] = []
note_type_created_hook: List[Callable[[Dict[str, Any]], None]] = [] note_type_created_hook: List[Callable[[Dict[str, Any]], None]] = []
odue_invalid_hook: List[Callable[[], None]] = [] odue_invalid_hook: List[Callable[[], None]] = []
original_card_template_filter: List[Callable[[str, bool], str]] = []
prepare_searches_hook: List[Callable[[Dict[str, Callable]], None]] = [] prepare_searches_hook: List[Callable[[Dict[str, Callable]], None]] = []
remove_notes_hook: List[Callable[[anki.storage._Collection, List[int]], None]] = [] remove_notes_hook: List[Callable[[anki.storage._Collection, List[int]], None]] = []
rendered_card_template_filter: List[ rendered_card_template_filter: List[
@ -183,6 +184,17 @@ def run_odue_invalid_hook() -> None:
raise raise
def run_original_card_template_filter(template: str, question_side: bool) -> str:
for filter in original_card_template_filter:
try:
template = filter(template, question_side)
except:
# if the hook fails, remove it
original_card_template_filter.remove(filter)
raise
return template
def run_prepare_searches_hook(searches: Dict[str, Callable]) -> None: def run_prepare_searches_hook(searches: Dict[str, Callable]) -> None:
for hook in prepare_searches_hook: for hook in prepare_searches_hook:
try: try:

View file

@ -59,6 +59,11 @@ hooks = [
name="modify_fields_for_rendering", name="modify_fields_for_rendering",
args=["fields: Dict[str, str]", "notetype: Dict[str, Any]", "data: QAData",], args=["fields: Dict[str, str]", "notetype: Dict[str, Any]", "data: QAData",],
), ),
Hook(
name="original_card_template",
args=["template: str", "question_side: bool"],
return_type="str",
),
Hook( Hook(
name="rendered_card_template", name="rendered_card_template",
args=[ args=[