diff --git a/docform/docx/richtext.py b/docform/docx/richtext.py index 4e7695f..5962d1f 100644 --- a/docform/docx/richtext.py +++ b/docform/docx/richtext.py @@ -7,6 +7,10 @@ except ImportError: # cgi.escape is deprecated in python 3.7 from cgi import escape +import re + +# A w:t element with at least one character in it. +_HAS_TEXT = re.compile(r"]*)?>[^<]") class RichText(object): @@ -121,6 +125,10 @@ def add( ) self.xml += xml + def __bool__(self): + """False when there's no text, so {%r if rt %} skips an empty RichText.""" + return bool(_HAS_TEXT.search(self.xml)) + def __unicode__(self): return self.xml @@ -140,7 +148,8 @@ class RichTextParagraph(object): def __init__(self, text=None, **text_prop): self.xml = "" - if text: + # An empty RichText is falsy but still makes an (empty) paragraph. + if isinstance(text, RichText) or text: self.add(text, **text_prop) def add( @@ -169,6 +178,10 @@ def add( xml += "" self.xml += xml + def __bool__(self): + """False when none of the paragraphs has any text.""" + return bool(_HAS_TEXT.search(self.xml)) + def __unicode__(self): return self.xml diff --git a/tests/unit/test_objects.py b/tests/unit/test_objects.py index 1a9058b..8545bbf 100644 --- a/tests/unit/test_objects.py +++ b/tests/unit/test_objects.py @@ -65,6 +65,37 @@ def test_richtext_link(make_docx): assert "w:hyperlink" in doc.paragraphs[0]._p.xml +def test_empty_richtext_is_falsy(): + assert not RichText() + assert not RichText("", color="0000FF") + empty_run = RichText() + empty_run.add("", bold=True) + assert not empty_run + assert RichText("x") + assert RichText(" ") + assert not RichTextParagraph() + assert not RichTextParagraph(RichText("")) + assert RichTextParagraph("x") + + +def test_empty_richtext_paragraph_still_renders_a_paragraph(): + assert RichTextParagraph(RichText("")).xml == "" + + +def test_if_skips_empty_richtext(make_docx): + text = ( + "{% for e in es %}{{ e.place }}" + "{%r if e.habitat %}; {{r e.habitat }}{%r endif %}.{% endfor %}" + ) + tpl = DocxTemplate(make_docx([text])) + entries = [ + {"place": "Boston", "habitat": RichText("forest", color="0000FF")}, + {"place": "Honolulu", "habitat": RichText("", color="0000FF")}, + ] + tpl.render({"es": entries}) + assert body_text(saved(tpl)) == ["Boston; forest.Honolulu."] + + def test_richtext_paragraph(make_docx): rp = RichTextParagraph() rp.add(RichText("first", bold=True))