Merge pull request #166 from mx2048/master

Fixed issue #159: autoescaped values for both str and unicode.
This commit is contained in:
Eric Lapouyade 2018-12-23 11:23:33 +01:00 committed by GitHub
commit bafdf1a310
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 10 deletions

View File

@ -267,9 +267,9 @@ class DocxTemplate(object):
identities.add(identity) identities.add(identity)
escape_recursively(v, identities) escape_recursively(v, identities)
else: else:
# Avoid dict, Listing, InlineImage, RichText, etc. classes # Avoid dict, Listing, InlineImage, RichText, etc classes
# by comparing `v` to `str`. Do not use try-except. # Do not use try-except.
if isinstance(v, str): if isinstance(v, six.string_types):
# Unescape at first to avoid secondary escaping # Unescape at first to avoid secondary escaping
d[k] = escape(unescape(v)) d[k] = escape(unescape(v))

View File

@ -1,13 +1,28 @@
from docxtpl import * """
@author: Max Podolskii
"""
import os
from unicodedata import name
from six import iteritems, text_type
from docxtpl import DocxTemplate
XML_RESERVED = """<"&'>"""
tpl = DocxTemplate('templates/escape_tpl_auto.docx') tpl = DocxTemplate('templates/escape_tpl_auto.docx')
context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'), context = {'nested_dict': {name(text_type(c)): c for c in XML_RESERVED},
'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ', 'autoescape': 'Escaped "str & ing"!',
'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'), 'autoescape_unicode': u'This is an escaped <unicode> example \u4f60 & \u6211',
'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&'), 'iteritems': iteritems,
'autoescape': """<, >, &, ", and '."""
} }
tpl.render(context, autoescape=True) tpl.render(context, autoescape=True)
tpl.save('output/escape_auto.docx')
OUTPUT = 'output'
if not os.path.exists(OUTPUT):
os.makedirs(OUTPUT)
tpl.save(OUTPUT + '/escape_auto.docx')

Binary file not shown.