python-docx-template icon indicating copy to clipboard operation
python-docx-template copied to clipboard

fix: allow % and } in {%p %}/{%tr %}/{%tc %}/{%r %} expressions

Open Bolt4243 opened this issue 5 months ago • 1 comments

Fixes #644.

patch_xml matched the expression body of these directive tags with [^}%]*, which stops at the first % or }. Tags whose expression contains a modulo (if i % 2 == 0) or a literal brace (set d = {"x":1}) were not stripped of their surrounding <w:p>/<w:tr>/<w:tc>/<w:r> wrapper, so the literal {%p ...%} reached Jinja and raised TemplateSyntaxError: Encountered unknown tag 'p'.

The fix matches up to the closing %}/}} instead of excluding those characters:

([^}%%]*(?:%%}|}}))  ->  ((?:(?!%%}|}}).)*(?:%%}|}}))

Verified with a real render: a template using {%p if i % 2 == 0 %} raises TemplateSyntaxError on the current code and renders correctly with the fix. The representative existing fixture tests (dynamic_table, nested_for, vertical_merge, horizontal_merge, less_cells_after_loop, comments, escape, merge_paragraph, richtext, order and others) still pass.

CI runs flake8 only and the existing tests are binary .docx fixtures with no assertions, so I did not add a fixture; the reproduction above is in the linked issue. Happy to add a fixture-based test if you prefer.

Bolt4243 avatar Jun 17 '26 03:06 Bolt4243

It would be better if you could add tests.

waketzheng avatar Jun 21 '26 04:06 waketzheng

Please include minimal example for new --validate option and expected user-facing messages.

arturict avatar Jul 13 '26 14:07 arturict