我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.template.loader.select_template()。
def get_template(self, request, *args, **kwargs): """Checks if there is a template with the page path, and uses that instead of using the generic page type template.""" page_template = '{0}.html'.format(self.url.strip('/')) logger.debug('get_template: page_template: {0}'.format(page_template)) default_template = super(BasePage, self).get_template(request, *args, **kwargs) logger.debug('get_template: default_template:{0}'.format( default_template)) template = select_template([page_template, default_template]) print template.template.name logger.debug('get_template: {0}'.format(template.template.name)) return template.template.name
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: template = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) response = HttpResponse(template.render({'flatpage': f}, request)) return response
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated: from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: template = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) response = HttpResponse(template.render({'flatpage': f}, request)) return response
def inclusion_tag(file_name, context_class=Context, takes_context=False): def wrap(func): @functools.wraps(func) def method(self, context, nodes, *arg, **kwargs): _dict = func(self, context, nodes, *arg, **kwargs) from django.template.loader import get_template, select_template if isinstance(file_name, Template): t = file_name elif not isinstance(file_name, basestring) and is_iterable(file_name): t = select_template(file_name) else: t = get_template(file_name) _dict['autoescape'] = context.autoescape _dict['use_l10n'] = context.use_l10n _dict['use_tz'] = context.use_tz _dict['admin_view'] = context['admin_view'] csrf_token = context.get('csrf_token', None) if csrf_token is not None: _dict['csrf_token'] = csrf_token nodes.append(t.render(_dict)) return method return wrap
def render(self, context, instance, placeholder): style_name = instance.get_style_name() style = instance.get_style() self.render_template = select_template(( self.TEMPLATE_NAME.format(style_name), self.TEMPLATE_NAME.format('default')) ) srcset = create_srcset(instance.image, style.get('widths'), style.get('aspect_ratio')) context.update({ 'srcset': srcset, 'sizes': style.get('sizes'), 'default_size': (style['default_width'], style['default_width']*style.get('aspect_ratio')), 'style': style_name, 'instance': instance, 'placeholder': placeholder }) return context
def send_message_template(sender, receiver, subject, template, context, *args, **kwargs): request = kwargs.get('request') if context is None: context = {} else: context = context.copy() context.setdefault('sender', sender) context.setdefault('receiver', receiver) context.setdefault('submission', kwargs.get('submission')) context.setdefault('ABSOLUTE_URL_PREFIX', settings.ABSOLUTE_URL_PREFIX) if isinstance(template, (tuple, list)): template = loader.select_template(template) if not hasattr(template, 'render'): template = loader.get_template(template) text = template.render(context, request) return send_message(sender, receiver, subject, text, *args, **kwargs)
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def get_render_template(self, request, instance, **kwargs): opts = type(instance.parent)._meta template = loader.select_template( [ 'icekit/plugins/image/%s_%s.html' % (opts.app_label, opts.model_name), 'icekit/plugins/image/%s.html' % opts.app_label, 'icekit/plugins/image/default.html' ] ) # In Django >= 1.8 `select_template` returns an instance of # `django.template.backends.django.Template` if the template exists. To obtain the # `django.template.base.Template` object we need to get the `template` attribute on it. # Previous versions of Django return a `django.template.base.Template` object. if hasattr(template, 'template'): template = template.template return template.name
def inclusion_tag(file_name, context_class=Context, takes_context=False): def wrap(func): @functools.wraps(func) def method(self, context, nodes, *arg, **kwargs): _dict = func(self, context, nodes, *arg, **kwargs) from django.template.loader import get_template, select_template if isinstance(file_name, Template): t = file_name elif not isinstance(file_name, str) and is_iterable(file_name): t = select_template(file_name) else: t = get_template(file_name) _dict['autoescape'] = context.autoescape _dict['use_l10n'] = context.use_l10n _dict['use_tz'] = context.use_tz _dict['admin_view'] = context['admin_view'] csrf_token = context.get('csrf_token', None) if csrf_token is not None: _dict['csrf_token'] = csrf_token nodes.append(t.render(_dict)) return method return wrap
def render(self, template_name, context): languages = self.get_languages(context['receiver']) template = select_template([ '{}.{}.email'.format(template_name, lang) for lang in languages ]) # Get the actually chosen language from the template name language = template.template.name.split('.', 2)[-2] with translation.override(language): parts = [] for part_type in ('subject', 'txt', 'html'): context['part_type'] = part_type parts.append(template.render(context)) context.pop('part_type') return tuple(parts)
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) return response
def render(self, context): hint_providers = [ var.resolve(context) for var in self.hint_provider_variables] hints = flatten( hint_provider.get_template_hints( name_provider=None, hint_providers=hint_providers) for hint_provider in hint_providers) template_names = [ var.resolve(context) for var in self.template_name_variables] template_names = flatten( [template_name.format(hint=hint) for hint in hints] for template_name in template_names) tpl = select_template(template_names) return tpl.render(context)
def _resolve_template(self): """ Thie code lifted from django.template.response.SimpleTemplateResponse, it resolves a string, list of strings, or template object into a valid template object. """ template = super().get_template_names() if isinstance(template, (list, tuple)): return select_template(template) elif isinstance(template, six.string_types): return get_template(template) else: return template
def inclusion_tag(file_name, context_class=Context, takes_context=False): def wrap(func): @functools.wraps(func) def method(self, context, nodes, *arg, **kwargs): _dict = func(self, context, nodes, *arg, **kwargs) from django.template.loader import get_template, select_template cls_str = str if 2 < sys.version_info.major else basestring if isinstance(file_name, Template): t = file_name elif not isinstance(file_name, cls_str) and is_iterable(file_name): t = select_template(file_name) else: t = get_template(file_name) _dict['autoescape'] = context.autoescape _dict['use_l10n'] = context.use_l10n _dict['use_tz'] = context.use_tz _dict['admin_view'] = context['admin_view'] csrf_token = context.get('csrf_token', None) if csrf_token is not None: _dict['csrf_token'] = csrf_token nodes.append(t.render(_dict)) return method return wrap