Skip to content

Commit 6fb9182

Browse files
authored
Merge pull request #210 from cvas22/perf/74-render-scaling
Make rendering large templates linear again
2 parents c415934 + 9b80742 commit 6fb9182

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

‎docform/docx/template.py‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,8 +724,20 @@ def build_xml(self, context, jinja_env=None):
724724

725725
def map_tree(self, tree):
726726
root = self.docx._element
727-
body = root.body
728-
root.replace(body, tree)
727+
# lxml takes quadratic time to move a large subtree from one document
728+
# to another, so replacing the body element (or moving its children)
729+
# dominated big renders (#74). Splice the rendered body into the
730+
# document's XML and parse it once instead.
731+
xml = etree.tostring(root, encoding="unicode")
732+
start = xml.find("<w:body")
733+
end = xml.rfind("</w:body>")
734+
if start < 0 or end < 0:
735+
root.replace(root.body, tree)
736+
else:
737+
body_xml = etree.tostring(tree, encoding="unicode")
738+
new_root = docx.oxml.parse_xml(xml[:start] + body_xml + xml[end + len("</w:body>"):])
739+
self.docx._element = new_root
740+
self.docx._part._element = new_root
729741
# python-docx caches its body wrapper, drop it so reads after
730742
# render() see the new body instead of the template one.
731743
if hasattr(self.docx, "_Document__body"):

‎tests/unit/test_render.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,3 +763,14 @@ def test_text_box_in_loop_gets_unique_ids(tmp_path):
763763
assert len(set(values)) == 3, (path_, values)
764764
# the first copy keeps the ids from the template
765765
assert etree._Element.xpath(body, "(.//v:shape)[1]/@o:spid", namespaces=ns) == ["_x0000_s1026"]
766+
767+
768+
def test_render_swaps_in_one_document_root(make_docx):
769+
tpl = DocxTemplate(make_docx(["{{ a }}", "{{ b }}"], table=[["{{ c }}"]]))
770+
tpl.render({"a": "one", "b": "two", "c": "three"})
771+
# the document and its part must share the rendered root, or save()
772+
# and python-docx reads would see different trees
773+
assert tpl.docx.element is tpl.docx.part.element
774+
assert [p.text for p in tpl.docx.paragraphs] == ["one", "two"]
775+
assert table_rows(tpl.docx) == [["three"]]
776+
assert body_text(saved(tpl)) == ["one", "two"]

0 commit comments

Comments
 (0)