passerelle/passerelle/utils/templates.py

61 lines
2.0 KiB
Python

# passerelle - uniform access to multiple data sources and services
# Copyright (C) 2020 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
'''Simplify rendering of template to produce text values.
Disable autoescaping.
'''
from django.core.exceptions import ValidationError
from django.template import Context, Template, TemplateSyntaxError
from django.template.backends.django import DjangoTemplates
from django.utils.translation import gettext as _
def make_template(template_string):
engine = DjangoTemplates(
{
'NAME': 'django',
'DIRS': [],
'APP_DIRS': False,
'OPTIONS': {'autoescape': False},
}
)
return engine.from_string(template_string)
def render_to_string(template_string, context):
return make_template(template_string).render(context=context)
def validate_template(template_string):
try:
make_template(template_string)
except TemplateSyntaxError as e:
raise ValidationError(_('Invalid template: %s') % e)
def evaluate_condition(condition_template, context_dict):
template = Template(f'{{% if {condition_template} %}}OK{{% endif %}}')
context = Context(context_dict)
return template.render(context) == 'OK'
def evaluate_template(template, context_dict):
template = Template(template)
context = Context(context_dict)
return template.render(context)