From 3403c35b1516d878eb69c2a0a0d212c417226cc0 Mon Sep 17 00:00:00 2001 From: AHMET ERCAN <294280988+ahmetmusab42-stack@users.noreply.github.com> Date: Wed, 2 Sep 2026 01:09:49 +0300 Subject: [PATCH] Fix cell backgrounds with self-closing tcPr --- docxtpl/template.py | 7 ++++++- tests/cellbg_shorthand.py | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/cellbg_shorthand.py diff --git a/docxtpl/template.py b/docxtpl/template.py index f20280a..e412f3a 100644 --- a/docxtpl/template.py +++ b/docxtpl/template.py @@ -135,7 +135,12 @@ def colspan(m): # manage table cell background color def cellbg(m): - cell_xml = m.group(1) + m.group(3) + cell_xml = re.sub( + r"]*)?/>", + r"", + m.group(1) + m.group(3), + count=1, + ) cell_xml = re.sub( r"](?:(?!]).)*.*?", "", diff --git a/tests/cellbg_shorthand.py b/tests/cellbg_shorthand.py new file mode 100644 index 0000000..5b77e53 --- /dev/null +++ b/tests/cellbg_shorthand.py @@ -0,0 +1,21 @@ +from lxml import etree + +from docxtpl import DocxTemplate + + +WORD_NAMESPACE = ( + "http://schemas.openxmlformats.org/wordprocessingml/2006/main" +) +SOURCE_XML = f""" + + + {{% cellbg background %}}content + +""" + +patched_xml = DocxTemplate(None).patch_xml(SOURCE_XML) +cell = etree.fromstring(patched_xml.encode()) +namespaces = {"w": WORD_NAMESPACE} + +assert len(cell.xpath("./w:tcPr/w:shd", namespaces=namespaces)) == 1 +assert len(cell.xpath("./w:shd", namespaces=namespaces)) == 0