You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

renderers.py 1.9KB

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