renderers.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import functools
  2. from pathlib import Path
  3. from django.conf import settings
  4. from django.template.backends.django import DjangoTemplates
  5. from django.template.loader import get_template
  6. from django.utils.functional import cached_property
  7. from django.utils.module_loading import import_string
  8. ROOT = Path(__file__).parent
  9. @functools.lru_cache()
  10. def get_default_renderer():
  11. renderer_class = import_string(settings.FORM_RENDERER)
  12. return renderer_class()
  13. class BaseRenderer:
  14. def get_template(self, template_name):
  15. raise NotImplementedError('subclasses must implement get_template()')
  16. def render(self, template_name, context, request=None):
  17. template = self.get_template(template_name)
  18. return template.render(context, request=request).strip()
  19. class EngineMixin:
  20. def get_template(self, template_name):
  21. return self.engine.get_template(template_name)
  22. @cached_property
  23. def engine(self):
  24. return self.backend({
  25. 'APP_DIRS': True,
  26. 'DIRS': [ROOT / self.backend.app_dirname],
  27. 'NAME': 'djangoforms',
  28. 'OPTIONS': {},
  29. })
  30. class DjangoTemplates(EngineMixin, BaseRenderer):
  31. """
  32. Load Django templates from the built-in widget templates in
  33. django/forms/templates and from apps' 'templates' directory.
  34. """
  35. backend = DjangoTemplates
  36. class Jinja2(EngineMixin, BaseRenderer):
  37. """
  38. Load Jinja2 templates from the built-in widget templates in
  39. django/forms/jinja2 and from apps' 'jinja2' directory.
  40. """
  41. @cached_property
  42. def backend(self):
  43. from django.template.backends.jinja2 import Jinja2
  44. return Jinja2
  45. class TemplatesSetting(BaseRenderer):
  46. """
  47. Load templates using template.loader.get_template() which is configured
  48. based on settings.TEMPLATES.
  49. """
  50. def get_template(self, template_name):
  51. return get_template(template_name)