Added support for jinja comments for paragraphs and table rows+cells

This commit is contained in:
Staffan Malmgren 2022-03-28 23:43:34 +02:00
parent 8a3c2051ad
commit 4e073ea451
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, strip all unnecessary xml tags, manage table cell background color and colspan,
unescape html entities, etc... """ unescape html entities, etc... """
# replace {<something>{ by {{ ( works with {{ }} {% and %} ) # replace {<something>{ by {{ ( works with {{ }} {% and %} {# and #})
src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})', '', src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})', '',
src_xml, flags=re.DOTALL) src_xml, flags=re.DOTALL)
# replace {{<some tags>jinja2 stuff<some other tags>}} by {{jinja2 stuff}} # 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 # "jinja2 stuff" could a variable, a 'if' etc... anything jinja2 will understand
def striptags(m): def striptags(m):
return re.sub('</w:t>.*?(<w:t>|<w:t [^>]*>)', '', return re.sub('</w:t>.*?(<w:t>|<w:t [^>]*>)', '',
m.group(0), flags=re.DOTALL) m.group(0), flags=re.DOTALL)
src_xml = re.sub(r'{%(?:(?!%}).)*|{{(?:(?!}}).)*', striptags, src_xml = re.sub(r'{%(?:(?!%}).)*|{#(?:(?!#}).)*|{{(?:(?!}}).)*', striptags,
src_xml, flags=re.DOTALL) src_xml, flags=re.DOTALL)
# manage table cell colspan # 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} 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) 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 # add vMerge
# use {% vm %} to make this table cell and its copies be vertically merged within a {% for %} # use {% vm %} to make this table cell and its copies be vertically merged within a {% for %}
def v_merge_tc(m): 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.