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() section_name = section_name.strip()
# check for cloze # check for cloze
val = None
m = re.match("c[qa]:(\d+):(.+)", section_name) m = re.match("c[qa]:(\d+):(.+)", section_name)
if m: if m:
# get full field text # get full field text
txt = get_or_attr(context, m.group(2), None) txt = get_or_attr(context, m.group(2), None)
m = re.search(clozeReg%m.group(1), txt) m = re.search(clozeReg%m.group(1), txt)
if m: if m:
it = m.group(1) val = m.group(1)
else:
it = None
else: else:
it = get_or_attr(context, section_name, None) val = get_or_attr(context, section_name, None)
replacer = '' replacer = ''
if isinstance(it, str): inverted = section[2] == "^"
it = stripHTMLMedia(it).strip() if (val and not inverted) or (not val and inverted):
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] == '^':
replacer = inner replacer = inner
template = template.replace(section, replacer) template = template.replace(section, replacer)

View file

@ -2,6 +2,7 @@
from tests.shared import getEmptyCol from tests.shared import getEmptyCol
from anki.utils import stripHTML, joinFields from anki.utils import stripHTML, joinFields
import anki.template
def test_modelDelete(): def test_modelDelete():
deck = getEmptyCol() deck = getEmptyCol()
@ -283,6 +284,14 @@ def test_modelChange():
deck.models.change(cloze, [f.id], basic, map, map) deck.models.change(cloze, [f.id], basic, map, map)
assert deck.db.scalar("select count() from cards where nid = ?", f.id) == 1 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(): def test_availOrds():
d = getEmptyCol() d = getEmptyCol()
m = d.models.current(); mm = d.models m = d.models.current(); mm = d.models