fix conditional templates

This commit is contained in:
Damien Elmes 2016-06-30 22:23:31 +10:00
parent ac7b081ece
commit 0c20da1069
2 changed files with 14 additions and 15 deletions

View file

@ -84,30 +84,20 @@ class Template(object):
section_name = section_name.strip()
# check for cloze
val = None
m = re.match("c[qa]:(\d+):(.+)", section_name)
if m:
# get full field text
txt = get_or_attr(context, m.group(2), None)
m = re.search(clozeReg%m.group(1), txt)
if m:
it = m.group(1)
val = m.group(1)
else:
it = None
else:
it = get_or_attr(context, section_name, None)
val = get_or_attr(context, section_name, None)
replacer = ''
if isinstance(it, str):
it = stripHTMLMedia(it).strip()
elif it and hasattr(it, 'keys') and hasattr(it, '__getitem__'):
if section[2] != '^':
replacer = self.render(inner, it)
elif it:
insides = []
for item in it:
insides.append(self.render(inner, item))
replacer = ''.join(insides)
elif not it and section[2] == '^':
inverted = section[2] == "^"
if (val and not inverted) or (not val and inverted):
replacer = inner
template = template.replace(section, replacer)

View file

@ -2,6 +2,7 @@
from tests.shared import getEmptyCol
from anki.utils import stripHTML, joinFields
import anki.template
def test_modelDelete():
deck = getEmptyCol()
@ -283,6 +284,14 @@ def test_modelChange():
deck.models.change(cloze, [f.id], basic, map, map)
assert deck.db.scalar("select count() from cards where nid = ?", f.id) == 1
def test_templates():
d = dict(Foo="x", Bar="y")
assert anki.template.render("{{Foo}}", d) == "x"
assert anki.template.render("{{#Foo}}{{Foo}}{{/Foo}}", d) == "x"
assert anki.template.render("{{#Foo}}{{Foo}}{{/Foo}}", d) == "x"
assert anki.template.render("{{#Bar}}{{#Foo}}{{Foo}}{{/Foo}}{{/Bar}}", d) == "x"
assert anki.template.render("{{#Baz}}{{#Foo}}{{Foo}}{{/Foo}}{{/Baz}}", d) == ""
def test_availOrds():
d = getEmptyCol()
m = d.models.current(); mm = d.models