mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
Fixed #15667 -- Added template-based widget rendering.
Thanks Carl Meyer and Tim Graham for contributing to the patch.
This commit is contained in:
committed by
Tim Graham
parent
51cde873d9
commit
b52c73008a
71
django/forms/renderers.py
Normal file
71
django/forms/renderers.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
|
||||
from django.conf import settings
|
||||
from django.template.backends.django import DjangoTemplates
|
||||
from django.template.loader import get_template
|
||||
from django.utils import lru_cache
|
||||
from django.utils._os import upath
|
||||
from django.utils.functional import cached_property
|
||||
from django.utils.module_loading import import_string
|
||||
|
||||
try:
|
||||
from django.template.backends.jinja2 import Jinja2
|
||||
except ImportError:
|
||||
def Jinja2(params):
|
||||
raise ImportError("jinja2 isn't installed")
|
||||
|
||||
ROOT = upath(os.path.dirname(__file__))
|
||||
|
||||
|
||||
@lru_cache.lru_cache()
|
||||
def get_default_renderer():
|
||||
renderer_class = import_string(settings.FORM_RENDERER)
|
||||
return renderer_class()
|
||||
|
||||
|
||||
class BaseRenderer(object):
|
||||
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()
|
||||
|
||||
|
||||
class EngineMixin(object):
|
||||
def get_template(self, template_name):
|
||||
return self.engine.get_template(template_name)
|
||||
|
||||
@cached_property
|
||||
def engine(self):
|
||||
return self.backend({
|
||||
'APP_DIRS': True,
|
||||
'DIRS': [os.path.join(ROOT, self.backend.app_dirname)],
|
||||
'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.
|
||||
"""
|
||||
backend = Jinja2
|
||||
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user