# HG changeset patch
# User cmlenz
# Date 1160751771 0
# Node ID 793d0af4766c2134216dcceb9492854192f5f358
# Parent 59f37556978666cb73657b51821dac7628503dca
Allow `when` directives to omit the test expression as long as the associated `choose` directive does have one. In that case, the `when` branch is followed if the expression of the `choose` directive evaluates to a truth value.
diff --git a/genshi/template.py b/genshi/template.py
--- a/genshi/template.py
+++ b/genshi/template.py
@@ -681,14 +681,18 @@
self.filename, *stream.next()[2][1:])
if matched:
return []
- if not self.expr:
- raise TemplateRuntimeError('"when" directive has no test condition',
+ if not self.expr and '_choose.value' not in frame:
+ raise TemplateRuntimeError('either "choose" or "when" directive '
+ 'must have a test expression',
self.filename, *stream.next()[2][1:])
- value = self.expr.evaluate(ctxt)
if '_choose.value' in frame:
- matched = (value == frame['_choose.value'])
+ value = frame['_choose.value']
+ if self.expr:
+ matched = value == self.expr.evaluate(ctxt)
+ else:
+ matched = bool(value)
else:
- matched = bool(value)
+ matched = bool(self.expr.evaluate(ctxt))
frame['_choose.matched'] = matched
if not matched:
return []
diff --git a/genshi/tests/template.py b/genshi/tests/template.py
--- a/genshi/tests/template.py
+++ b/genshi/tests/template.py
@@ -198,6 +198,21 @@
""")
self.assertRaises(TemplateRuntimeError, str, tmpl.generate())
+ def test_when_without_test_but_with_choose_value(self):
+ """
+ Verify that an `when` directive that doesn't have a `test` attribute
+ works as expected as long as the parent `choose` directive has a test
+ expression.
+ """
+ tmpl = MarkupTemplate("""
+
+ """)
+ self.assertEqual("""
+ foo
+ """, str(tmpl.generate(foo='Yeah')))
+
def test_otherwise_without_test(self):
"""
Verify that an `otherwise` directive can be used without a `test`