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

# Between adjacent text nodes, allow run boundaries and font properties.
# Other elements, such as tabs and line breaks, interrupt the delimiter.
run_markup = r"</?w:r\b[^>]*>|<w:rPr/>|<w:rPr>(?:<[^<>]+/>)*</w:rPr>"
split_run_gap = rf"(?:</w:t>(?:{run_markup})*<w:t\b[^>]*>)?"
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
61 changes: 61 additions & 0 deletions tests/escaping_delimiters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
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_{")

# Empty and formatted runs do not add text.
paragraph = template.add_paragraph()
paragraph.add_run("left }")
paragraph.add_run()
paragraph.add_run("_").bold = True
paragraph.add_run("} right")

# A tab or line break is visible content, even when Word gives it a separate run.
for separator in ("\t", "\n"):
paragraph = template.add_paragraph()
paragraph.add_run("left }")
paragraph.add_run(separator)
paragraph.add_run("_} right")

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_{",
"left }} right",
"left }\t_} right",
"left }\n_} right",
]