1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

Fixed #23516 -- Added caching of include tag Template objects

This also speeds up for loops that render the same template
multiple times.
This commit is contained in:
Matthew Somerville
2015-06-04 12:50:07 +01:00
committed by Tim Graham
parent 2a7c59cd88
commit a391b17ad2
3 changed files with 31 additions and 2 deletions

View File

@@ -171,6 +171,8 @@ class ExtendsNode(Node):
class IncludeNode(Node):
context_key = '__include_context'
def __init__(self, template, *args, **kwargs):
self.template = template
self.extra_context = kwargs.pop('extra_context', {})
@@ -178,12 +180,22 @@ class IncludeNode(Node):
super(IncludeNode, self).__init__(*args, **kwargs)
def render(self, context):
"""
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
"""
try:
template = self.template.resolve(context)
# Does this quack like a Template?
if not callable(getattr(template, 'render', None)):
# If not, we'll try get_template
template = context.template.engine.get_template(template)
# If not, we'll try our cache, and get_template()
template_name = template
cache = context.render_context.setdefault(self.context_key, {})
template = cache.get(template_name)
if template is None:
template = context.template.engine.get_template(template_name)
cache[template_name] = template
values = {
name: var.resolve(context)
for name, var in six.iteritems(self.extra_context)