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
27 changes: 26 additions & 1 deletion docform/docx/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,28 @@ def write_xml(self, filename):
with open(filename, "w", encoding="utf-8") as fh:
fh.write(self.get_xml())

@staticmethod
def _keep_section_break(m):
"""Replace a {%p %} paragraph by its tag, keeping a section break.

A paragraph that ends a section holds the section's settings (page
size, margins, orientation) in w:pPr/w:sectPr. Dropping it with the
tag would merge the section into the next one. Keep an empty
paragraph with those properties outside the block: before an
opening tag and after a closing one, so it's never skipped or
repeated by the tag.
"""
tag = m.group(1) + " " + m.group(2)
ppr = re.search(
r"<w:pPr>(?:(?!</w:pPr>).)*<w:sectPr[ >/].*?</w:pPr>", m.group(0), flags=re.DOTALL
)
if ppr is None:
return tag
section_break = "<w:p>" + ppr.group(0) + "</w:p>"
if re.match(r"-?\s*end", m.group(2)):
return tag + section_break
return section_break + tag

def patch_xml(self, src_xml):
"""Make a lots of cleaning to have a raw xml understandable by jinja2 :
strip all unnecessary xml tags, manage table cell background color and colspan,
Expand Down Expand Up @@ -404,7 +426,10 @@ def cellbg(m):
r"<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ((?:(?!%%}|}}).)*(?:%%}|}})).*?</w:%(y)s>"
% {"y": y}
)
src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL)
if y == "p":
src_xml = re.sub(pat, self._keep_section_break, src_xml, flags=re.DOTALL)
else:
src_xml = re.sub(pat, r"\1 \2", src_xml, flags=re.DOTALL)

for y in ["tr", "tc", "p"]:
# same thing, but for {#y xxx #} (but not where y == 'r', since that
Expand Down
36 changes: 36 additions & 0 deletions tests/unit/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,42 @@ def test_hm_keeps_tcpr_in_schema_order(tmp_path):
assert names == sorted(names, key=TC_PR_ORDER.index)


@pytest.mark.parametrize(
"paragraphs, break_at, context",
[
(["{%p if show %}", "{{ text }}", "{%p endif %}"], 0, {"show": True}),
(["{%p if show %}", "{{ text }}", "{%p endif %}"], 0, {"show": False}),
(["{%p if show %}", "{{ text }}", "{%p endif %}"], 2, {"show": True}),
(["{%p if show %}", "{{ text }}", "{%p endif %}"], 2, {"show": False}),
(["{%p for x in xs %}", "{{ x }}", "{%p endfor %}"], 0, {"xs": [1, 2, 3]}),
(["{%p for x in xs %}", "{{ x }}", "{%p endfor %}"], 2, {"xs": [1, 2, 3]}),
],
ids=["if-shown", "if-hidden", "endif-shown", "endif-hidden", "for", "endfor"],
)
def test_section_break_on_paragraph_tag_is_kept(tmp_path, paragraphs, break_at, context):
from docx.shared import Inches

doc = Document()
for index, text in enumerate(paragraphs):
if index == break_at:
# python-docx puts the section break in a new last paragraph
doc.add_section()
doc.paragraphs[-1].text = text
else:
doc.add_paragraph(text)
doc.sections[0].left_margin = Inches(2)
path = tmp_path / "sections.docx"
doc.save(str(path))

tpl = DocxTemplate(str(path))
tpl.render(dict(context, text="body"))
out = saved(tpl)
assert len(out.sections) == 2
assert out.sections[0].left_margin == Inches(2)
assert out.sections[1].left_margin != Inches(2)
assert not any("{%" in text for text in body_text(out))


def test_header_footer_and_properties(make_docx):
path = make_docx(["body {{ x }}"], header="head {{ x }}", footer="foot {{ x }}", title="Report {{ x }}")
tpl = DocxTemplate(path)
Expand Down
Loading