Skip to content
Open
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
9 changes: 9 additions & 0 deletions docxtpl/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ def patch_xml(self, src_xml):
strip all unnecessary xml tags, manage table cell background color and colspan,
unescape html entities, etc..."""

# Join escaped Jinja delimiters that Word has split across runs. Limit the
# removable XML to tags inside one paragraph so unrelated text is untouched.
split_run_gap = (
r"(?:</w:t>(?:(?!</?w:p(?:\s|>))<[^>]+>)*<w:t(?: [^>]*)?>)?"
)
for escaped_delimiter in ("{_{", "}_}", "{_%", "%_}"):
pattern = split_run_gap.join(map(re.escape, escaped_delimiter))
src_xml = re.sub(pattern, escaped_delimiter, src_xml)

# replace {<something>{ by {{ ( works with {{ }} {% and %} {# and #})
src_xml = re.sub(
r"(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})",
Expand Down
43 changes: 43 additions & 0 deletions tests/escaping_delimiters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from pathlib import Path

from docx import Document
from docxtpl import DocxTemplate


output_dir = Path(__file__).parent / "output"
output_dir.mkdir(exist_ok=True)
template_path = output_dir / "escaping_delimiters_split_tpl.docx"
result_path = output_dir / "escaping_delimiters_split.docx"

escaped_delimiters = ("{_%", "%_}", "{_{", "}_}")
expected_delimiters = ("{%", "%}", "{{", "}}")

template = Document()

for delimiter in escaped_delimiters:
template.add_paragraph(delimiter)

template.add_paragraph()

for delimiter in escaped_delimiters:
paragraph = template.add_paragraph()
for character in delimiter:
paragraph.add_run(character)

# These are not escaped delimiters and must not be changed.
template.add_paragraph("{a_{hello")
template.add_paragraph("{f_{")
template.save(template_path)

doc = DocxTemplate(template_path)
doc.render({})
doc.save(result_path)

paragraphs = [paragraph.text for paragraph in Document(result_path).paragraphs]
assert paragraphs == [
*expected_delimiters,
"",
*expected_delimiters,
"{a_{hello",
"{f_{",
]