|
1 |
# authentic2 - versatile identity manager
|
|
2 |
# Copyright (C) 2010-2020 Entr'ouvert
|
|
3 |
#
|
|
4 |
# This program is free software: you can redistribute it and/or modify it
|
|
5 |
# under the terms of the GNU Affero General Public License as published
|
|
6 |
# by the Free Software Foundation, either version 3 of the License, or
|
|
7 |
# (at your option) any later version.
|
|
8 |
#
|
|
9 |
# This program is distributed in the hope that it will be useful,
|
|
10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12 |
# GNU Affero General Public License for more details.
|
|
13 |
#
|
|
14 |
# You should have received a copy of the GNU Affero General Public License
|
|
15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
16 |
|
|
17 |
from django.template import VariableDoesNotExist as DjangoVariableDoesNotExist
|
|
18 |
from django.template import engines
|
|
19 |
from django.template import TemplateSyntaxError as DjangoTemplateSyntaxError
|
|
20 |
from django.utils.encoding import force_str
|
|
21 |
from django.utils.translation import ugettext_lazy as _
|
|
22 |
|
|
23 |
|
|
24 |
class TemplateError(Exception):
|
|
25 |
pass
|
|
26 |
|
|
27 |
|
|
28 |
class Template(object):
|
|
29 |
def __init__(self, value, raises=False, autoescape=False):
|
|
30 |
self.value = value
|
|
31 |
self.raises = raises
|
|
32 |
|
|
33 |
if not autoescape:
|
|
34 |
self.value = '{%% autescape off %%}%s{%% endautoescape %%}' % \
|
|
35 |
self.value
|
|
36 |
try:
|
|
37 |
self.template = engines['django'].from_string(value)
|
|
38 |
except DjangoTemplateSyntaxError as e:
|
|
39 |
if self.raises:
|
|
40 |
raise TemplateError(_('template syntax error: %s') % e)
|
|
41 |
# no rendering
|
|
42 |
self.render = lambda x,y: str(x.value)
|
|
43 |
else:
|
|
44 |
self.render = self.django_render
|
|
45 |
|
|
46 |
def django_render(self, context={}):
|
|
47 |
excepted = False
|
|
48 |
try:
|
|
49 |
rendered = self.template.render(context)
|
|
50 |
except DjangoTemplateSyntaxError as e:
|
|
51 |
if raises:
|
|
52 |
raise TemplateError(_('template syntax error: %s') % e)
|
|
53 |
except DjangoVariableDoesNotExist as e:
|
|
54 |
if raises:
|
|
55 |
raise TemplateError(_('template variable missing: %s') % e)
|
|
56 |
else:
|
|
57 |
return force_str(rendered)
|
|
58 |
return force_str(self.value)
|
0 |
|
-
|