From 0218258a156c0fddb06a0da4f641a6e1d601cb40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Wed, 20 Dec 2017 15:57:53 +0100 Subject: [PATCH] templates: fix encoding handling in django templates (#20831) --- tests/test_templates.py | 5 +++++ wcs/qommon/template.py | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/test_templates.py b/tests/test_templates.py index 54edf4b57..afd5b8a10 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -66,6 +66,11 @@ def test_template_encoding(): assert tmpl.render({'foo': 'fou'}) == 'fou à vélo' assert tmpl.render({'foo': 'félé'}) == 'félé à vélo' + tmpl = Template("{% if foo == 'félé' %}à vélo{% endif %}") + assert tmpl.render() == '' + assert tmpl.render({'foo': 'fou'}) == '' + assert tmpl.render({'foo': 'félé'}) == 'à vélo' + # ezt tmpl = Template('[foo] à vélo') assert tmpl.render() == '[foo] à vélo' diff --git a/wcs/qommon/template.py b/wcs/qommon/template.py index c9c549cde..d0ae94ded 100644 --- a/wcs/qommon/template.py +++ b/wcs/qommon/template.py @@ -449,6 +449,14 @@ def ezt_raises(exception, on_parse=False): raise TemplateError(message % ' '.join(parts)) +class UnicodeDjangoContext(DjangoContext): + def __getitem__(self, key): + s = super(UnicodeDjangoContext, self).__getitem__(key) + if isinstance(s, str): + return unicode(s, 'utf-8') + return s + + class Template(object): def __init__(self, value, raises=False, ezt_format=ezt.FORMAT_RAW, ezt_only=False): '''Guess kind of template (Django or ezt), and parse it''' @@ -482,7 +490,7 @@ class Template(object): return str(self.value) def django_render(self, context={}): - context = DjangoContext(context) + context = UnicodeDjangoContext(context) try: rendered = self.template.render(context) except (DjangoTemplateSyntaxError, DjangoVariableDoesNotExist) as e: