def get_default_template_context_processors(engine_name='django'): """Return all default template context processors for an engine. Args: engine_name (unicode): When run on Django 1.8 or higher, this specifies which template engine's context processors to return. On Django 1.7 and older, this is ignored. Returns: list of callable: The list of template context processors. Raises: django.core.exceptions.ImproperlyConfigured: The specified template engine wasn't valid on this version of Django. """ if template_engines is None: return get_standard_processors() else: try: template_engine = template_engines[engine_name] except KeyError: raise ImproperlyConfigured( 'The "%s" template engine must be defined.' % engine_name) return template_engine.engine.template_context_processors
def process_response(self, request, response): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info) self.record_stats({ 'templates': template_context, 'template_dirs': [here('../templates')], 'context_processors': context_processors, })
def enhanced_init(self, request, dict_=None, processors=None, current_app=None, use_l10n=None, use_tz=None): Context.__init__(self, dict_, current_app=current_app, use_l10n=use_l10n, use_tz=use_tz) if processors is None: processors = () else: processors = tuple(processors) #update by bery at 20150728 if dict_: page_title = dict_.get('page_title', '') else: page_title = '' try: request.context_dict = dict_ except: context_dict = {} context_dict['page_title'] = page_title request.context_dict = context_dict for processor in get_standard_processors() + processors: self.update(processor(request))
def process_response(self, request, response): context_processors = dict([("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors()]) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info) self.record_stats({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, })
def __init__(self, request, dict=None, processors=None, current_app=None, use_l10n=None): if not dict: dict = {} # 基础配置信息 configuration = Configuration.objects.filter() if configuration: dict['configuration'] = configuration[0] # ‘公共’尾部信息 foot_items = FootItem.objects.filter(is_display=True).order_by('order') if foot_items: dict['foot_items'] = foot_items Context.__init__(self, dict, current_app=current_app, use_l10n=use_l10n) if processors is None: processors = () else: processors = tuple(processors) for processor in get_standard_processors() + processors: self.update(processor(request))
def render(request, template, context=None, **kwargs): """ Shortcut like Django's ``render_to_response``, but better. Minimal usage, with only a request object and a template name:: return jingo.render(request, 'template.html') With template context and keywords passed to :class:`django.http.HttpResponse`:: return jingo.render(request, 'template.html', {'some_var': 42}, status=209) """ if not _helpers_loaded: load_helpers() if context is None: context = {} for processor in get_standard_processors(): context.update(processor(request)) # If it's not a Template, it must be a path to be loaded. if not isinstance(template, jinja2.environment.Template): template = env.get_template(template) rendered = template.render(**context) return http.HttpResponse(rendered, **kwargs)
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for i, d in enumerate(self.templates): info = {} # Clean up some info about templates t = d.get('template', None) # Skip templates that we are generating through the debug toolbar. if t.name.startswith('debug_toolbar/'): continue if t.origin and t.origin.name: t.origin_name = t.origin.name else: t.origin_name = 'No origin' info['template'] = t # Clean up context for better readability c = d.get('context', None) info['context'] = '\n'.join([pformat(_d) for _d in c.dicts]) template_context.append(info) context = { 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, } return render_to_string('debug_toolbar/panels/templates.html', context)
def process_response(self, request, response): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if self.toolbar.config['SHOW_TEMPLATE_CONTEXT']: context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info) self.record_stats({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, })
def content(self): context_processors = dict([("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors()]) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) # Skip templates that we are generating through the debug toolbar. if hasattr(template, 'name') and template.name.startswith('debug_toolbar/'): continue if hasattr(template, 'origin') and hasattr(template.origin, 'name'): template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_data = template_data.get('context', None) context_list = [] for context_layer in context_data.dicts: if hasattr(context_layer, 'items'): for key, value in context_layer.items(): # Replace any request elements - they have a large # unicode representation and the request data is # already made available from the Request Vars panel. if isinstance(value, http.HttpRequest): context_layer[key] = '<<request>>' # Replace the debugging sql_queries element. The SQL # data is already made available from the SQL panel. elif key == 'sql_queries' and isinstance( value, list): context_layer[key] = '<<sql_queries>>' # Replace LANGUAGES, which is available in i18n context processor elif key == 'LANGUAGES' and isinstance( value, tuple): context_layer[key] = '<<languages>>' try: context_list.append(pformat(context_layer)) except UnicodeEncodeError: pass info['context'] = '\n'.join(context_list) template_context.append(info) context = self.context.copy() context.update({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, }) return render_to_string('debug_toolbar/panels/templates.html', context)
def render_to_string(template_name, context=None, request=None, processors=None): """Render a template into a string.""" context = dict(context or {}) if request is not None: context['request'] = request for processor in chain(get_standard_processors(), processors or ()): context.update(processor(request)) return get_template(template_name).render(context)
def get_standard_processors(self): """Get django standart processors """ try: from django.template.context import get_standard_processors return get_standard_processors() except Exception: return []
def test_csrf_token_context_processor(self): # Our CSRF token should be available in the template context. request = mock.Mock() request.csrf_token = self.token request.groups = [] ctx = {} for processor in context.get_standard_processors(): ctx.update(processor(request)) self.assertEqual(ctx['csrf_token'], self.token)
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) # Skip templates that we are generating through the debug toolbar. if template.name and template.name.startswith('debug_toolbar/'): continue if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_data = template_data.get('context', None) context_list = [] for context_layer in context_data.dicts: if hasattr(context_layer, 'items'): for key, value in context_layer.items(): # Replace any request elements - they have a large # unicode representation and the request data is # already made available from the Request Vars panel. if isinstance(value, http.HttpRequest): context_layer[key] = '<<request>>' # Replace the debugging sql_queries element. The SQL # data is already made available from the SQL panel. elif key == 'sql_queries' and isinstance(value, list): context_layer[key] = '<<sql_queries>>' # Replace LANGUAGES, which is available in i18n context processor elif key == 'LANGUAGES' and isinstance(value, tuple): context_layer[key] = '<<languages>>' try: context_list.append(pformat(context_layer)) except UnicodeEncodeError: pass info['context'] = '\n'.join(context_list) template_context.append(info) context = self.context.copy() context.update({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, }) return render_to_string('debug_toolbar/panels/templates.html', context)
def render_xml_to_string(request, template, context={}): if not jingo._helpers_loaded: jingo.load_helpers() for processor in get_standard_processors(): context.update(processor(request)) template = xml_env.get_template(template) return template.render(context)
def render_xml_to_string(request, template, context={}): if not jingo._helpers_loaded: jingo.load_helpers() for processor in get_standard_processors(): context.update(processor(request)) template = xml_env.get_template(template) return template.render(**context)
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) # Skip templates that we are generating through the debug toolbar. if template.name.startswith('debug_toolbar/'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_data = template_data.get('context', None) context_list = [] for depth, context_layer in enumerate(context_data.dicts): safe_context_layer = [] for key, value in context_layer.iteritems(): # Replace any request elements - they have a large # unicode representation and the request data is # already made available from the Request Vars panel. if isinstance(value, http.HttpRequest): value = '<a href="#" class="djDebugRequestVarsPanel">%s instance</a>' % escape(type(value)) # Replace the debugging sql_queries element. The SQL # data is already made available from the SQL panel. elif key == 'sql_queries' and isinstance(value, list): value = '<a href="#" class="djDebugSQLPanel">list of SQL queries</a>' # Otherwise, just format and escape the value. else: try: value = pformat(value) except UnicodeEncodeError: value = '<value could not be encoded to unicode>' value = escape(value) safe_context_layer.append((key, mark_safe(value))) safe_context_layer.sort() context_list.append((depth, safe_context_layer)) info['context'] = context_list template_context.append(info) context = { 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, } return render_to_string('debug_toolbar/panels/templates.html', context)
def __init__(self, dict=None, processors=None, current_app=None): Context.__init__(self, dict, current_app=current_app) if processors is None: processors = () else: processors = tuple(processors) for processor in ( tuple(p for p in get_standard_processors() if getattr(p, "requires_request", True) == False) + processors ): self.update(processor())
def render_to_response(self, context): template = TEMPLATE_ENV.get_template(self.template_name) context['TEMPLATE_NAME'] = self.template_name.split('/')[-1].split('.')[0] for processor in get_standard_processors(): context.update(processor(self.request)) response = HttpResponse(content=template.render(**context)) response.template_name = self.template_name return response
def get_context(): c = {} if context is None else context.copy() try: from django.template.context import get_standard_processors for processor in get_standard_processors(): c.update(processor(request)) except ImportError: pass return c
def render_xml(request, template, context={}, **kwargs): """Safely renders xml, stripping out nasty control characters.""" if not jingo._helpers_loaded: jingo.load_helpers() for processor in get_standard_processors(): context.update(processor(request)) template = xml_env.get_template(template) rendered = template.render(**context) return HttpResponse(rendered, **kwargs)
def render_to_string(template_name, context=None, request=None): """Render a template into a string.""" if context is None: context = {} if request is not None: context['request'] = request for processor in get_standard_processors(): context.update(processor(request)) try: return get_template(template_name).render(context) except jinja2.TemplateSyntaxError, e: raise TemplateSyntaxError(e.message, e.lineno, e.name, e.filename)
def render_to_string(template_name, context=None, request=None, processors=None): """Render a template into a string.""" context = dict(context or {}) if request is not None: context['request'] = request context_instance = RequestContext(request) for processor in chain(get_standard_processors(), processors or ()): context.update(processor(request)) else: context_instance = None return shortcuts.render_to_string(template_name, context, context_instance)
def __init__(self, request, dict=None, processors=None): Context.__init__(self, dict) if processors is None: processors = () else: processors = tuple(processors) for processor in get_standard_processors(): self.update(processor(request)) for processor in processors: self.update(processor(request, self))
def get_template_context_processors(): """Compatibility method to fetch the template context processors.""" if Engine: try: engine = Engine.get_default() except ImproperlyConfigured: context_processors = [] else: context_processors = engine.template_context_processors else: # Django < 1.8 context_processors = get_standard_processors() return context_processors
def render_to_string(template, context={}, request=None): """Render a template to a string.""" assert env is not None, 'Jinja not configured for django' if request is not None: # It's very important to apply these in a specific order default_context = { 'request': request, } for processor in get_standard_processors(): default_context.update(processor(request)) default_context.update(context) context = default_context template = env.get_template(template) return template.render(context)
def get_context_processors(): """Get context processors in a way that works for Django 1.7 and 1.8+""" try: # 1.7 from django.template.context import get_standard_processors return get_standard_processors() except ImportError: # 1.8+ try: from django.template.engine import Engine engine = Engine.get_default() except ImproperlyConfigured: return [] return engine.template_context_processors
def render_xml(request, template, context={}, **kwargs): """Safely renders xml, stripping out nasty control characters.""" if not jingo._helpers_loaded: jingo.load_helpers() for processor in get_standard_processors(): context.update(processor(request)) template = xml_env.get_template(template) rendered = template.render(**context) if 'mimetype' not in kwargs: kwargs['mimetype'] = 'text/xml' return HttpResponse(rendered, **kwargs)
def render(self): tpl = loader.get_template(self.template) context = self._default_context if getattr(settings, "TEMPLATE_EMAIL_USE_CONTEXT_PROCESSORS", False): if Engine: standard_processors = Engine.get_default().template_context_processors else: standard_processors = get_standard_processors() for processor in standard_processors: try: context.update(processor(None)) except: pass context.update(self.context) context.update(self._override_context) context_subject = dict(context, _subject=True) context_body = dict(context, _body=True) context_html = dict(context, _bodyhtml=True) subject = tpl.render(Context(context_subject)).strip() body = tpl.render(Context(context_body)).strip() html = tpl.render(Context(context_html)).strip() if subject != '': self.subject = subject if body != '': self.body = body if html != '': html_doc = None base_url = getattr(settings, "TEMPLATE_EMAIL_BASE_URL", None) if base_url: html_doc = html_doc or lxml.html.fromstring(html) html_doc.make_links_absolute(base_url) if getattr(settings, "TEMPLATE_EMAIL_INLINE_CSS", False): html_doc = html_doc or lxml.html.fromstring(html) opts = getattr( settings, "TEMPLATE_EMAIL_INLINE_CSS_OPTIONS", {}) html_doc = premailer.Premailer(html_doc, **opts).transform() if html_doc: html = lxml.html.tostring( html_doc, include_meta_content_type=True).decode('utf-8') self.html = html self._rendered = True
def resolve_context(self, context): """Change the context object into a dictionary (what Jinja uses), and go through all our context processors from settings.""" # get me a dictionary if context: self.context_data = dict(context) else: self.context_data = {} # I still want to keep the use of my Django context processors # even though this is a Jinja template; therefore, process them manually for context_processor in get_standard_processors(): new_stuff = context_processor(self._request) if new_stuff: self.context_data.update(dict(new_stuff)) # return a flat dict; jinja doesn't have context objects return self.context_data
def render(self): tpl = loader.get_template(self.template) context = self._default_context if getattr(settings, "TEMPLATE_EMAIL_USE_CONTEXT_PROCESSORS", False): for processor in get_standard_processors(): try: context.update(processor(None)) except: pass context.update(self.context) context.update(self._override_context) context_subject = dict(context, _subject=True) context_body = dict(context, _body=True) context_html = dict(context, _bodyhtml=True) subject = tpl.render(Context(context_subject)).strip() body = tpl.render(Context(context_body)).strip() html = tpl.render(Context(context_html)).strip() if subject != '': self.subject = subject if body != '': self.body = body if html != '': html_doc = None base_url = getattr(settings, "TEMPLATE_EMAIL_BASE_URL", None) if base_url: html_doc = html_doc or lxml.html.fromstring(html) html_doc.make_links_absolute(base_url) if getattr(settings, "TEMPLATE_EMAIL_INLINE_CSS", False): html_doc = html_doc or lxml.html.fromstring(html) opts = getattr( settings, "TEMPLATE_EMAIL_INLINE_CSS_OPTIONS", {}) html_doc = premailer.Premailer(html_doc, **opts).transform() if html_doc: html = lxml.html.tostring( html_doc, include_meta_content_type=True).decode('utf-8') self.html = html self._rendered = True
def process_response(self, request, response): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] templates = dict() for template_data in self.templates: info = {} # Clean up some info about templates if 'template' in template_data: template = template_data['template'] else: class template(object): name = template_data['filename'] if hasattr(template, 'origin') and hasattr(template.origin, 'name'): template.origin_name = template.origin.name else: template.origin_name = 'No origin' if template.name in templates: continue else: templates[template.name] = None info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info) self.record_stats({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, })
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for i, d in enumerate(self.templates): info = {} # Clean up some info about templates t = d.get('template', None) # Skip templates that we are generating through the debug toolbar. if t.name.startswith('debug_toolbar/'): continue if t.origin and t.origin.name: t.origin_name = t.origin.name else: t.origin_name = 'No origin' info['template'] = t # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): c = d.get('context', None) d_list = [] for _d in c.dicts: try: d_list.append(pformat(d)) except UnicodeEncodeError: pass info['context'] = '\n'.join(d_list) template_context.append(info) context = { 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, } return render_to_string('debug_toolbar/panels/templates.html', context)
def render_to_string(request, template, ctxt=None): """Render a template to a string.""" context = ctxt if ctxt is not None else {} if request is not None: context['request'] = request # skip non essential context processors for error pages if template not in ('404.html', '500.html'): # include django context processors for processor in get_standard_processors(): for key, value in processor(request).items(): if key not in context: context[key] = value else: from django.core.context_processors import request as django_request from extensions.context_processors import settings_ processors = (django_request, settings_) for processor in processors: for key, value in processor(request).items(): if key not in context: context[key] = value template = env.get_template(template) return template.render(context)
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) # Skip templates that we are generating through the debug toolbar. if template.name and template.name.startswith('debug_toolbar/'): continue if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = 'No origin' info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info) context = self.context.copy() context.update({ 'templates': template_context, 'template_dirs': [normpath(x) for x in settings.TEMPLATE_DIRS], 'context_processors': context_processors, }) return render_to_string('debug_toolbar/panels/templates.html', context)
def content(self): context_processors = dict( [ ("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors() ] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get('template', None) # Skip templates that we are generating through the debug toolbar. if hasattr(template, 'name') and template.name.startswith('debug_toolbar/'): continue if not hasattr(template, 'origin'): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: try: template.origin_name = 'No origin' except AttributeError, e: # Mako will sometimes output unicode strings not # template objects. Attempting to set an # attribute on a unicode object will fail, so we # catch this condition and move along. pass info['template'] = template # Clean up context for better readability if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('SHOW_TEMPLATE_CONTEXT', True): context_list = template_data.get('context', []) info['context'] = '\n'.join(context_list) template_context.append(info)
def process_request(self, request): self.context_processors = dict( [("%s.%s" % (k.__module__, k.__name__), pformat(k(request))) for k in get_standard_processors()] )
def get_context(): c = {} if context is None else context.copy() for processor in get_standard_processors(): c.update(processor(request)) return c
def render_to_string(filename, context={}, request=None): template = environment.get_or_select_template(filename) if request: for processor in get_standard_processors(): context.update(processor(request)) return template.render(context)
def content(self): context_processors = dict( [("%s.%s" % (k.__module__, k.__name__), pformat(k(self.request))) for k in get_standard_processors()] ) template_context = [] for template_data in self.templates: info = {} # Clean up some info about templates template = template_data.get("template", None) # Skip templates that we are generating through the debug toolbar. if template.name and template.name.startswith("debug_toolbar/"): continue if not hasattr(template, "origin"): continue if template.origin and template.origin.name: template.origin_name = template.origin.name else: template.origin_name = "No origin" info["template"] = template # Clean up context for better readability if getattr(settings, "DEBUG_TOOLBAR_CONFIG", {}).get("SHOW_TEMPLATE_CONTEXT", True): context_list = template_data.get("context", []) info["context"] = "\n".join(context_list) template_context.append(info) context = self.context.copy() context.update( { "templates": template_context, "template_dirs": [normpath(x) for x in settings.TEMPLATE_DIRS], "context_processors": context_processors, } ) return render_to_string("debug_toolbar/panels/templates.html", context)