MCPcopy Create free account
hub / github.com/elapouya/python-docx-template / patch_xml

Method patch_xml

docxtpl/template.py:85–303  ·  view source on GitHub ↗

Make a lots of cleaning to have a raw xml understandable by jinja2 : strip all unnecessary xml tags, manage table cell background color and colspan, unescape html entities, etc...

(self, src_xml)

Source from the content-addressed store, hash-verified

83 fh.write(self.get_xml())
84
85 def patch_xml(self, src_xml):
86 """Make a lots of cleaning to have a raw xml understandable by jinja2 :
87 strip all unnecessary xml tags, manage table cell background color and colspan,
88 unescape html entities, etc..."""
89
90 # replace {<something>{ by {{ ( works with {{ }} {% and %} {# and #})
91 src_xml = re.sub(
92 r"(?<={)(<[^>]*>)+(?=[\{%\#])|(?<=[%\}\#])(<[^>]*>)+(?=\})",
93 "",
94 src_xml,
95 flags=re.DOTALL,
96 )
97
98 # replace {{<some tags>jinja2 stuff<some other tags>}} by {{jinja2 stuff}}
99 # same thing with {% ... %} and {# #}
100 # "jinja2 stuff" could a variable, a 'if' etc... anything jinja2 will understand
101 def striptags(m):
102 return re.sub(
103 "</w:t>.*?(<w:t>|<w:t [^>]*>)", "", m.group(0), flags=re.DOTALL
104 )
105
106 src_xml = re.sub(
107 r"{%(?:(?!%}).)*|{#(?:(?!#}).)*|{{(?:(?!}}).)*",
108 striptags,
109 src_xml,
110 flags=re.DOTALL,
111 )
112
113 # manage table cell colspan
114 def colspan(m):
115 cell_xml = m.group(1) + m.group(3)
116 cell_xml = re.sub(
117 r"<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>",
118 "",
119 cell_xml,
120 flags=re.DOTALL,
121 )
122 cell_xml = re.sub(r"<w:gridSpan[^/]*/>", "", cell_xml, count=1)
123 return re.sub(
124 r"(<w:tcPr[^>]*>)",
125 r'\1<w:gridSpan w:val="{{%s}}"/>' % m.group(2),
126 cell_xml,
127 )
128
129 src_xml = re.sub(
130 r"(<w:tc[ >](?:(?!<w:tc[ >]).)*){%\s*colspan\s+([^%]*)\s*%}(.*?</w:tc>)",
131 colspan,
132 src_xml,
133 flags=re.DOTALL,
134 )
135
136 # manage table cell background color
137 def cellbg(m):
138 cell_xml = m.group(1) + m.group(3)
139 cell_xml = re.sub(
140 r"<w:r[ >](?:(?!<w:r[ >]).)*<w:t></w:t>.*?</w:r>",
141 "",
142 cell_xml,

Callers 4

render_footnotesMethod · 0.95
build_xmlMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected