This commit is contained in:
Eric Lapouyade 2022-04-16 10:55:42 +02:00
commit b4e533ae66
3 changed files with 17 additions and 4 deletions

View File

@ -77,17 +77,17 @@ class DocxTemplate(object):
strip all unnecessary xml tags, manage table cell background color and colspan,
unescape html entities, etc... """
# replace {<something>{ by {{ ( works with {{ }} {% and %} )
src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})', '',
# replace {<something>{ by {{ ( works with {{ }} {% and %} {# and #})
src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})', '',
src_xml, flags=re.DOTALL)
# replace {{<some tags>jinja2 stuff<some other tags>}} by {{jinja2 stuff}}
# same thing with {% ... %}
# same thing with {% ... %} and {# #}
# "jinja2 stuff" could a variable, a 'if' etc... anything jinja2 will understand
def striptags(m):
return re.sub('</w:t>.*?(<w:t>|<w:t [^>]*>)', '',
m.group(0), flags=re.DOTALL)
src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*', striptags,
src_xml = re.sub(r'{%(?:(?!%}).)*|{#(?:(?!#}).)*|{{(?:(?!}}).)*', striptags,
src_xml, flags=re.DOTALL)
# manage table cell colspan
@ -134,6 +134,12 @@ class DocxTemplate(object):
pat = r'<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>' % {'y': y}
src_xml = re.sub(pat, r'\1 \2', src_xml, flags=re.DOTALL)
for y in ['tr', 'tc', 'p']:
# same thing, but for {#y xxx #} (but not where y == 'r', since that
# makes less sense to use comments in that context
pat = r'<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({#)%(y)s ([^}#]*(?:#})).*?</w:%(y)s>' % {'y': y}
src_xml = re.sub(pat, r'\1 \2', src_xml, flags=re.DOTALL)
# add vMerge
# use {% vm %} to make this table cell and its copies be vertically merged within a {% for %}
def v_merge_tc(m):

7
tests/comments.py Normal file
View File

@ -0,0 +1,7 @@
import sys, os
from docxtpl import DocxTemplate
tpl = DocxTemplate('templates/comments.docx')
tpl.render({})
tpl.save('output/comments.docx')

Binary file not shown.