diff --git a/docxtpl/template.py b/docxtpl/template.py index 3c97202..79be84a 100644 --- a/docxtpl/template.py +++ b/docxtpl/template.py @@ -77,17 +77,17 @@ class DocxTemplate(object): strip all unnecessary xml tags, manage table cell background color and colspan, unescape html entities, etc... """ - # replace {{ by {{ ( works with {{ }} {% and %} ) - src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%])|(?<=[%\}])(<[^>]*>)+(?=\})', '', + # replace {{ by {{ ( works with {{ }} {% and %} {# and #}) + src_xml = re.sub(r'(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})', '', src_xml, flags=re.DOTALL) # replace {{jinja2 stuff}} 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('.*?(|]*>)', '', 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'](?:(?!]).)*({%%|{{)%(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'](?:(?!]).)*({#)%(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): diff --git a/tests/comments.py b/tests/comments.py new file mode 100644 index 0000000..9fe6146 --- /dev/null +++ b/tests/comments.py @@ -0,0 +1,7 @@ +import sys, os +from docxtpl import DocxTemplate + +tpl = DocxTemplate('templates/comments.docx') + +tpl.render({}) +tpl.save('output/comments.docx') diff --git a/tests/templates/comments.docx b/tests/templates/comments.docx new file mode 100644 index 0000000..d341bab Binary files /dev/null and b/tests/templates/comments.docx differ