Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion docform/docx/richtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"<w:t(?:\s[^>]*)?>[^<]")


class RichText(object):
Expand Down Expand Up @@ -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

Expand All @@ -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(
Expand Down Expand Up @@ -169,6 +178,10 @@ def add(
xml += "</w:p>"
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

Expand Down
31 changes: 31 additions & 0 deletions tests/unit/test_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "<w:p></w:p>"


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))
Expand Down
Loading