2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
2017-07-22 04:33:26 +08:00
|
|
|
from pathlib import Path
|
2016-12-28 06:00:56 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
|
|
|
from django.template.backends.django import DjangoTemplates
|
|
|
|
from django.template.loader import get_template
|
|
|
|
from django.utils.functional import cached_property
|
|
|
|
from django.utils.module_loading import import_string
|
|
|
|
|
2017-07-22 04:33:26 +08:00
|
|
|
ROOT = Path(__file__).parent
|
2016-12-28 06:00:56 +08:00
|
|
|
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache()
|
2016-12-28 06:00:56 +08:00
|
|
|
def get_default_renderer():
|
|
|
|
renderer_class = import_string(settings.FORM_RENDERER)
|
|
|
|
return renderer_class()
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class BaseRenderer:
|
2016-12-28 06:00:56 +08:00
|
|
|
def get_template(self, template_name):
|
|
|
|
raise NotImplementedError('subclasses must implement get_template()')
|
|
|
|
|
|
|
|
def render(self, template_name, context, request=None):
|
|
|
|
template = self.get_template(template_name)
|
|
|
|
return template.render(context, request=request).strip()
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class EngineMixin:
|
2016-12-28 06:00:56 +08:00
|
|
|
def get_template(self, template_name):
|
|
|
|
return self.engine.get_template(template_name)
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def engine(self):
|
|
|
|
return self.backend({
|
|
|
|
'APP_DIRS': True,
|
2019-11-07 17:26:22 +08:00
|
|
|
'DIRS': [ROOT / self.backend.app_dirname],
|
2016-12-28 06:00:56 +08:00
|
|
|
'NAME': 'djangoforms',
|
|
|
|
'OPTIONS': {},
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
class DjangoTemplates(EngineMixin, BaseRenderer):
|
|
|
|
"""
|
|
|
|
Load Django templates from the built-in widget templates in
|
|
|
|
django/forms/templates and from apps' 'templates' directory.
|
|
|
|
"""
|
|
|
|
backend = DjangoTemplates
|
|
|
|
|
|
|
|
|
|
|
|
class Jinja2(EngineMixin, BaseRenderer):
|
|
|
|
"""
|
|
|
|
Load Jinja2 templates from the built-in widget templates in
|
|
|
|
django/forms/jinja2 and from apps' 'jinja2' directory.
|
|
|
|
"""
|
2020-09-22 15:53:17 +08:00
|
|
|
@cached_property
|
|
|
|
def backend(self):
|
|
|
|
from django.template.backends.jinja2 import Jinja2
|
|
|
|
return Jinja2
|
2016-12-28 06:00:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
class TemplatesSetting(BaseRenderer):
|
|
|
|
"""
|
|
|
|
Load templates using template.loader.get_template() which is configured
|
|
|
|
based on settings.TEMPLATES.
|
|
|
|
"""
|
|
|
|
def get_template(self, template_name):
|
|
|
|
return get_template(template_name)
|