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
16 changes: 14 additions & 2 deletions docform/docx/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,8 +724,20 @@ def build_xml(self, context, jinja_env=None):

def map_tree(self, tree):
root = self.docx._element
body = root.body
root.replace(body, tree)
# lxml takes quadratic time to move a large subtree from one document
# to another, so replacing the body element (or moving its children)
# dominated big renders (#74). Splice the rendered body into the
# document's XML and parse it once instead.
xml = etree.tostring(root, encoding="unicode")
start = xml.find("<w:body")
end = xml.rfind("</w:body>")
if start < 0 or end < 0:
root.replace(root.body, tree)
else:
body_xml = etree.tostring(tree, encoding="unicode")
new_root = docx.oxml.parse_xml(xml[:start] + body_xml + xml[end + len("</w:body>"):])
self.docx._element = new_root
self.docx._part._element = new_root
# python-docx caches its body wrapper, drop it so reads after
# render() see the new body instead of the template one.
if hasattr(self.docx, "_Document__body"):
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -763,3 +763,14 @@ def test_text_box_in_loop_gets_unique_ids(tmp_path):
assert len(set(values)) == 3, (path_, values)
# the first copy keeps the ids from the template
assert etree._Element.xpath(body, "(.//v:shape)[1]/@o:spid", namespaces=ns) == ["_x0000_s1026"]


def test_render_swaps_in_one_document_root(make_docx):
tpl = DocxTemplate(make_docx(["{{ a }}", "{{ b }}"], table=[["{{ c }}"]]))
tpl.render({"a": "one", "b": "two", "c": "three"})
# the document and its part must share the rendered root, or save()
# and python-docx reads would see different trees
assert tpl.docx.element is tpl.docx.part.element
assert [p.text for p in tpl.docx.paragraphs] == ["one", "two"]
assert table_rows(tpl.docx) == [["three"]]
assert body_text(saved(tpl)) == ["one", "two"]
Loading