Index: django/test/utils.py
===================================================================
--- django/test/utils.py	(revision 11374)
+++ django/test/utils.py	(working copy)
@@ -54,8 +54,8 @@
         - Diverting the email sending functions to a test buffer
         - Setting the active locale to match the LANGUAGE_CODE setting.
     """
-    Template.original_render = Template.render
-    Template.render = instrumented_test_render
+    Template.original_render = Template._render
+    Template._render = instrumented_test_render
 
     mail.original_SMTPConnection = mail.SMTPConnection
     mail.SMTPConnection = TestSMTPConnection
@@ -71,7 +71,7 @@
         - Restoring the email sending functions
 
     """
-    Template.render = Template.original_render
+    Template._render = Template.original_render
     del Template.original_render
 
     mail.SMTPConnection = mail.original_SMTPConnection
Index: django/template/__init__.py
===================================================================
--- django/template/__init__.py	(revision 11374)
+++ django/template/__init__.py	(working copy)
@@ -173,10 +173,17 @@
             for subnode in node:
                 yield subnode
 
-    def render(self, context):
-        "Display stage -- can be called many times"
+    def _render(self, context):
         return self.nodelist.render(context)
 
+    def render(self, context, push_parser_context=True):
+        "Display stage -- can be called many times"
+        context.parser_context.push()
+        try:
+            return self._render(context)
+        finally:
+            context.parser_context.pop()
+
 def compile_string(template_string, origin):
     "Compiles template_string into NodeList ready for rendering"
     if settings.TEMPLATE_DEBUG:
Index: django/template/loaders/app_directories.py
===================================================================
--- django/template/loaders/app_directories.py	(revision 11374)
+++ django/template/loaders/app_directories.py	(working copy)
@@ -9,6 +9,7 @@
 from django.conf import settings
 from django.core.exceptions import ImproperlyConfigured
 from django.template import TemplateDoesNotExist
+from django.template.loader import BaseLoader
 from django.utils._os import safe_join
 from django.utils.importlib import import_module
 
@@ -27,29 +28,38 @@
 # It won't change, so convert it to a tuple to save memory.
 app_template_dirs = tuple(app_template_dirs)
 
-def get_template_sources(template_name, template_dirs=None):
-    """
-    Returns the absolute paths to "template_name", when appended to each
-    directory in "template_dirs". Any paths that don't lie inside one of the
-    template dirs are excluded from the result set, for security reasons.
-    """
-    if not template_dirs:
-        template_dirs = app_template_dirs
-    for template_dir in template_dirs:
-        try:
-            yield safe_join(template_dir, template_name)
-        except UnicodeDecodeError:
-            # The template dir name was a bytestring that wasn't valid UTF-8.
-            raise
-        except ValueError:
-            # The joined path was located outside of template_dir.
-            pass
+class Loader(BaseLoader):
+    is_usable = True
 
+    def get_template_sources(self, template_name, template_dirs=None):
+        """
+        Returns the absolute paths to "template_name", when appended to each
+        directory in "template_dirs". Any paths that don't lie inside one of the
+        template dirs are excluded from the result set, for security reasons.
+        """
+        if not template_dirs:
+            template_dirs = app_template_dirs
+        for template_dir in template_dirs:
+            try:
+                yield safe_join(template_dir, template_name)
+            except UnicodeDecodeError:
+                # The template dir name was a bytestring that wasn't valid UTF-8.
+                raise
+            except ValueError:
+                # The joined path was located outside of template_dir.
+                pass
+
+    def load_template_source(self, template_name, template_dirs=None):
+        for filepath in self.get_template_sources(template_name, template_dirs):
+            try:
+                return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
+            except IOError:
+                pass
+        raise TemplateDoesNotExist, template_name
+
+loader = Loader()
+
 def load_template_source(template_name, template_dirs=None):
-    for filepath in get_template_sources(template_name, template_dirs):
-        try:
-            return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
-        except IOError:
-            pass
-    raise TemplateDoesNotExist, template_name
+    # For backwards compatibility
+    return loader.load_template_source(template_name, template_dirs)
 load_template_source.is_usable = True
Index: django/template/loaders/filesystem.py
===================================================================
--- django/template/loaders/filesystem.py	(revision 11374)
+++ django/template/loaders/filesystem.py	(working copy)
@@ -4,38 +4,49 @@
 
 from django.conf import settings
 from django.template import TemplateDoesNotExist
+from django.template.loader import BaseLoader
 from django.utils._os import safe_join
 
-def get_template_sources(template_name, template_dirs=None):
-    """
-    Returns the absolute paths to "template_name", when appended to each
-    directory in "template_dirs". Any paths that don't lie inside one of the
-    template dirs are excluded from the result set, for security reasons.
-    """
-    if not template_dirs:
-        template_dirs = settings.TEMPLATE_DIRS
-    for template_dir in template_dirs:
-        try:
-            yield safe_join(template_dir, template_name)
-        except UnicodeDecodeError:
-            # The template dir name was a bytestring that wasn't valid UTF-8.
-            raise
-        except ValueError:
-            # The joined path was located outside of this particular
-            # template_dir (it might be inside another one, so this isn't
-            # fatal).
-            pass
+class Loader(BaseLoader):
+    is_usable = True
 
+    def get_template_sources(self, template_name, template_dirs=None):
+        """
+        Returns the absolute paths to "template_name", when appended to each
+        directory in "template_dirs". Any paths that don't lie inside one of the
+        template dirs are excluded from the result set, for security reasons.
+        """
+        if not template_dirs:
+            template_dirs = settings.TEMPLATE_DIRS
+        for template_dir in template_dirs:
+            try:
+                yield safe_join(template_dir, template_name)
+            except UnicodeDecodeError:
+                # The template dir name was a bytestring that wasn't valid UTF-8.
+                raise
+            except ValueError:
+                # The joined path was located outside of this particular
+                # template_dir (it might be inside another one, so this isn't
+                # fatal).
+                pass
+
+    def load_template_source(self, template_name, template_dirs=None):
+        tried = []
+        for filepath in self.get_template_sources(template_name, template_dirs):
+            try:
+                return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
+            except IOError:
+                tried.append(filepath)
+        if tried:
+            error_msg = "Tried %s" % tried
+        else:
+            error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
+        raise TemplateDoesNotExist, error_msg
+    load_template_source.is_usable = True
+
+loader = Loader()
+
 def load_template_source(template_name, template_dirs=None):
-    tried = []
-    for filepath in get_template_sources(template_name, template_dirs):
-        try:
-            return (open(filepath).read().decode(settings.FILE_CHARSET), filepath)
-        except IOError:
-            tried.append(filepath)
-    if tried:
-        error_msg = "Tried %s" % tried
-    else:
-        error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
-    raise TemplateDoesNotExist, error_msg
+    # For backwards compatibility
+    return loader.load_template_source(template_name, template_dirs)
 load_template_source.is_usable = True
Index: django/template/loaders/eggs.py
===================================================================
--- django/template/loaders/eggs.py	(revision 11374)
+++ django/template/loaders/eggs.py	(working copy)
@@ -6,20 +6,29 @@
     resource_string = None
 
 from django.template import TemplateDoesNotExist
+from django.template.loader import BaseLoader
 from django.conf import settings
 
+class Loader(BaseLoader):
+    is_usable = resource_string is not None
+
+    def load_template_source(self, template_name, template_dirs=None):
+        """
+        Loads templates from Python eggs via pkg_resource.resource_string.
+
+        For every installed app, it tries to get the resource (app, template_name).
+        """
+        if resource_string is not None:
+            pkg_name = 'templates/' + template_name
+            for app in settings.INSTALLED_APPS:
+                try:
+                    return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name))
+                except:
+                    pass
+        raise TemplateDoesNotExist, template_name
+
+loader = Loader()
+
 def load_template_source(template_name, template_dirs=None):
-    """
-    Loads templates from Python eggs via pkg_resource.resource_string.
-
-    For every installed app, it tries to get the resource (app, template_name).
-    """
-    if resource_string is not None:
-        pkg_name = 'templates/' + template_name
-        for app in settings.INSTALLED_APPS:
-            try:
-                return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name))
-            except:
-                pass
-    raise TemplateDoesNotExist, template_name
+    return loader.load_template_source(template_name, template_dirs)
 load_template_source.is_usable = resource_string is not None
Index: django/template/loaders/cached.py
===================================================================
--- django/template/loaders/cached.py	(revision 0)
+++ django/template/loaders/cached.py	(revision 0)
@@ -0,0 +1,46 @@
+"""
+Wrapper class that takes a list of template loaders as an argument and attempts
+to load templates from them in order, caching the result.
+"""
+
+from django.template import TemplateDoesNotExist
+from django.template.loader import BaseLoader, get_template_from_string, find_template_loader, make_origin
+from django.utils.importlib import import_module
+from django.core.exceptions import ImproperlyConfigured
+
+class Loader(BaseLoader):
+    is_usable = True
+    template_cache = {}
+
+    def __init__(self, loaders):
+        self._loaders = loaders
+        self._cached_loaders = []
+
+    @property
+    def loaders(self):
+        # Resolve loaders on demand to avoid circular imports
+        if not self._cached_loaders:
+            for loader in self._loaders:
+                self._cached_loaders.append(find_template_loader(loader))
+        return self._cached_loaders
+
+    def find_template(self, name, dirs=None):
+        for loader in self.loaders:
+            try:
+                template, display_name = loader(name, dirs)
+                return (template, make_origin(display_name, loader, name, dirs))
+            except TemplateDoesNotExist:
+                pass
+        raise TemplateDoesNotExist, name
+
+    def load_template(self, template_name, template_dirs=None):
+        if template_name not in self.template_cache:
+            template, origin = self.find_template(template_name, template_dirs)
+            if not hasattr(template, 'render'):
+                template = get_template_from_string(template, origin, template_name)
+            self.template_cache[template_name] = (template, origin)
+        return self.template_cache[template_name]
+
+    def reset(self):
+        "Empty the template cache."
+        self.template_cache = {}
Index: django/template/defaulttags.py
===================================================================
--- django/template/defaulttags.py	(revision 11374)
+++ django/template/defaulttags.py	(working copy)
@@ -39,11 +39,14 @@
 
 class CycleNode(Node):
     def __init__(self, cyclevars, variable_name=None):
-        self.cycle_iter = itertools_cycle(cyclevars)
+        self.cyclevars = cyclevars
         self.variable_name = variable_name
 
     def render(self, context):
-        value = self.cycle_iter.next().resolve(context)
+        if self not in context.parser_context:
+            context.parser_context[self] = {'cycle_iter': itertools_cycle(self.cyclevars)}
+        cycle_iter = context.parser_context[self]['cycle_iter']
+        value = cycle_iter.next().resolve(context)
         if self.variable_name:
             context[self.variable_name] = value
         return value
Index: django/template/context.py
===================================================================
--- django/template/context.py	(revision 11374)
+++ django/template/context.py	(working copy)
@@ -7,45 +7,42 @@
     "pop() has been called more times than push()"
     pass
 
-class Context(object):
-    "A stack container for variable context"
-    def __init__(self, dict_=None, autoescape=True, current_app=None):
+class BaseContext(object):
+    def __init__(self, dict_=None):
         dict_ = dict_ or {}
         self.dicts = [dict_]
-        self.autoescape = autoescape
-        self.current_app = current_app
 
     def __repr__(self):
         return repr(self.dicts)
 
     def __iter__(self):
-        for d in self.dicts:
+        for d in reversed(self.dicts):
             yield d
-
+    
     def push(self):
         d = {}
-        self.dicts = [d] + self.dicts
+        self.dicts.append(d)
         return d
 
     def pop(self):
         if len(self.dicts) == 1:
             raise ContextPopException
-        return self.dicts.pop(0)
+        return self.dicts.pop()
 
     def __setitem__(self, key, value):
         "Set a variable in the current context"
-        self.dicts[0][key] = value
+        self.dicts[-1][key] = value
 
     def __getitem__(self, key):
         "Get a variable's value, starting at the current context and going upward"
-        for d in self.dicts:
+        for d in reversed(self.dicts):
             if key in d:
                 return d[key]
         raise KeyError(key)
 
     def __delitem__(self, key):
         "Delete a variable from the current context"
-        del self.dicts[0][key]
+        del self.dicts[-1][key]
 
     def has_key(self, key):
         for d in self.dicts:
@@ -53,7 +50,8 @@
                 return True
         return False
 
-    __contains__ = has_key
+    def __contains__(self, key):
+        return self.has_key(key)
 
     def get(self, key, otherwise=None):
         for d in self.dicts:
@@ -61,13 +59,37 @@
                 return d[key]
         return otherwise
 
+
+class Context(BaseContext):
+    "A stack container for variable context"
+    def __init__(self, dict_=None, autoescape=True, current_app=None):
+        self.autoescape = autoescape
+        self.current_app = current_app
+        self.parser_context = ParserContext()
+        super(Context, self).__init__(dict_)
+
     def update(self, other_dict):
         "Like dict.update(). Pushes an entire dictionary's keys and values onto the context."
         if not hasattr(other_dict, '__getitem__'):
             raise TypeError('other_dict must be a mapping (dictionary-like) object.')
-        self.dicts = [other_dict] + self.dicts
+        self.dicts.append(other_dict)
         return other_dict
 
+class ParserContext(BaseContext):
+    """A stack container for storing Template state."""
+    def __iter__(self):
+        for d in self.dicts[-1]:
+            yield d
+
+    def has_key(self, key):
+        return key in self.dicts[-1]
+
+    def get(self, key, otherwise=None):
+        d = self.dicts[-1]
+        if key in d:
+            return d[key]
+        return otherwise
+
 # This is a function rather than module-level procedural code because we only
 # want it to execute if somebody uses RequestContext.
 def get_standard_processors():
Index: django/template/loader_tags.py
===================================================================
--- django/template/loader_tags.py	(revision 11374)
+++ django/template/loader_tags.py	(working copy)
@@ -1,14 +1,43 @@
 from django.template import TemplateSyntaxError, TemplateDoesNotExist, Variable
 from django.template import Library, Node, TextNode
-from django.template.loader import get_template, get_template_from_string, find_template_source
+from django.template.loader import get_template
 from django.conf import settings
 from django.utils.safestring import mark_safe
 
 register = Library()
 
+BLOCK_CONTEXT_KEY = 'block_context'
+
 class ExtendsError(Exception):
     pass
 
+class BlockContext(object):
+    def __init__(self):
+        # Dictionary of FIFO queues.
+        self.blocks = {}
+
+    def add_blocks(self, blocks):
+        for name, block in blocks.iteritems():
+            if name in self.blocks:
+                self.blocks[name].insert(0, block)
+            else:
+                self.blocks[name] = [block]
+
+    def pop(self, name):
+        try:
+            return self.blocks[name].pop()
+        except (IndexError, KeyError):
+            return None
+
+    def push(self, name, block):
+        self.blocks[name].append(block)
+
+    def get_block(self, name):
+        try:
+            return self.blocks[name][-1]
+        except (IndexError, KeyError):
+            return None
+
 class BlockNode(Node):
     def __init__(self, name, nodelist, parent=None):
         self.name, self.nodelist, self.parent = name, nodelist, parent
@@ -17,25 +46,32 @@
         return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist)
 
     def render(self, context):
+        block_context = context.parser_context.get(BLOCK_CONTEXT_KEY, None)
         context.push()
-        # Save context in case of block.super().
-        self.context = context
-        context['block'] = self
-        result = self.nodelist.render(context)
+        if block_context is None:
+            context['block'] = self
+            result = self.nodelist.render(context)
+        else:
+            push = block = block_context.pop(self.name)
+            if block is None:
+                block = self
+            # Create new block so we can store context without thread-safety issues.
+            block = BlockNode(block.name, block.nodelist)
+            block.context = context
+            context['block'] = block
+            result = block.nodelist.render(context)
+            if push is not None:
+                block_context.push(self.name, push)
         context.pop()
         return result
 
     def super(self):
-        if self.parent:
-            return mark_safe(self.parent.render(self.context))
+        parser_context = self.context.parser_context
+        if (BLOCK_CONTEXT_KEY in parser_context and
+            parser_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None):
+            return mark_safe(self.render(self.context))
         return ''
 
-    def add_parent(self, nodelist):
-        if self.parent:
-            self.parent.add_parent(nodelist)
-        else:
-            self.parent = BlockNode(self.name, nodelist)
-
 class ExtendsNode(Node):
     must_be_first = True
 
@@ -43,7 +79,8 @@
         self.nodelist = nodelist
         self.parent_name, self.parent_name_expr = parent_name, parent_name_expr
         self.template_dirs = template_dirs
-
+        self.blocks = dict([(n.name, n) for n in nodelist.get_nodes_by_type(BlockNode)])
+ 
     def __repr__(self):
         if self.parent_name_expr:
             return "<ExtendsNode: extends %s>" % self.parent_name_expr.token
@@ -61,41 +98,35 @@
         if hasattr(parent, 'render'):
             return parent # parent is a Template object
         try:
-            source, origin = find_template_source(parent, self.template_dirs)
+            return get_template(parent)
         except TemplateDoesNotExist:
             raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
-        else:
-            return get_template_from_string(source, origin, parent)
 
     def render(self, context):
         compiled_parent = self.get_parent(context)
-        parent_blocks = dict([(n.name, n) for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
-        for block_node in self.nodelist.get_nodes_by_type(BlockNode):
-            # Check for a BlockNode with this node's name, and replace it if found.
-            try:
-                parent_block = parent_blocks[block_node.name]
-            except KeyError:
-                # This BlockNode wasn't found in the parent template, but the
-                # parent block might be defined in the parent's *parent*, so we
-                # add this BlockNode to the parent's ExtendsNode nodelist, so
-                # it'll be checked when the parent node's render() is called.
 
-                # Find out if the parent template has a parent itself
-                for node in compiled_parent.nodelist:
-                    if not isinstance(node, TextNode):
-                        # If the first non-text node is an extends, handle it.
-                        if isinstance(node, ExtendsNode):
-                            node.nodelist.append(block_node)
-                        # Extends must be the first non-text node, so once you find
-                        # the first non-text node you can stop looking. 
-                        break
-            else:
-                # Keep any existing parents and add a new one. Used by BlockNode.
-                parent_block.parent = block_node.parent
-                parent_block.add_parent(parent_block.nodelist)
-                parent_block.nodelist = block_node.nodelist
-        return compiled_parent.render(context)
+        if BLOCK_CONTEXT_KEY not in context.parser_context:
+            context.parser_context[BLOCK_CONTEXT_KEY] = BlockContext()
+        block_context = context.parser_context[BLOCK_CONTEXT_KEY]
 
+        # Add the block nodes from this node to the block context
+        block_context.add_blocks(self.blocks)
+
+        # If this block's parent doesn't have an extends node it is the root,
+        # and its block nodes also need to be added to the block context.
+        for node in compiled_parent.nodelist:
+            # The ExtendsNode has to be the first non-text node.
+            if not isinstance(node, TextNode):
+                if not isinstance(node, ExtendsNode):
+                    blocks = dict([(n.name, n) for n in
+                                   compiled_parent.nodelist.get_nodes_by_type(BlockNode)])
+                    block_context.add_blocks(blocks)
+                break
+
+        # Call Template._render explicitly so the parser context stays
+        # the same.
+        return compiled_parent._render(context)
+
 class ConstantIncludeNode(Node):
     def __init__(self, template_path):
         try:
Index: django/template/loader.py
===================================================================
--- django/template/loader.py	(revision 11374)
+++ django/template/loader.py	(working copy)
@@ -27,6 +27,33 @@
 
 template_source_loaders = None
 
+class BaseLoader(object):
+    is_usable = False
+
+    def __call__(self, template_name, template_dirs=None):
+        return self.load_template(template_name, template_dirs)
+
+    def load_template(self, template_name, template_dirs=None):
+        source, origin = self.load_template_source(template_name, template_dirs)
+        template = get_template_from_string(source, name=template_name)
+        return template, origin
+    
+    def load_template_source(self, template_name, template_dirs=None):
+        """
+        Returns a tuple containing the source and origin for the given template
+        name.
+
+        """
+        raise NotImplementedError
+
+    def reset(self):
+        """
+        Resets any state maintained by the loader instance (e.g., cached
+        templates or cached loader modules).
+
+        """
+        pass
+
 class LoaderOrigin(Origin):
     def __init__(self, display_name, loader, name, dirs):
         super(LoaderOrigin, self).__init__(display_name)
@@ -41,29 +68,37 @@
     else:
         return None
 
-def find_template_source(name, dirs=None):
+def find_template_loader(loader):
+    if callable(loader):
+        return loader
+    elif isinstance(loader, basestring):
+        i = loader.rfind('.')
+        module, attr = loader[:i], loader[i+1:]
+        try:
+            mod = import_module(module)
+        except ImportError, e:
+            raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e)
+        try:
+            func = getattr(mod, attr)
+        except AttributeError:
+            raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr)
+        if not func.is_usable:
+            import warnings
+            warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % loader)
+        else:
+            return func
+    else:
+        raise ImproperlyConfigured, 'Loader does not define a "load_template" callable template source loader'
+
+def find_template(name, dirs=None):
     # Calculate template_source_loaders the first time the function is executed
     # because putting this logic in the module-level namespace may cause
     # circular import errors. See Django ticket #1292.
     global template_source_loaders
     if template_source_loaders is None:
         loaders = []
-        for path in settings.TEMPLATE_LOADERS:
-            i = path.rfind('.')
-            module, attr = path[:i], path[i+1:]
-            try:
-                mod = import_module(module)
-            except ImportError, e:
-                raise ImproperlyConfigured, 'Error importing template source loader %s: "%s"' % (module, e)
-            try:
-                func = getattr(mod, attr)
-            except AttributeError:
-                raise ImproperlyConfigured, 'Module "%s" does not define a "%s" callable template source loader' % (module, attr)
-            if not func.is_usable:
-                import warnings
-                warnings.warn("Your TEMPLATE_LOADERS setting includes %r, but your Python installation doesn't support that type of template loading. Consider removing that line from TEMPLATE_LOADERS." % path)
-            else:
-                loaders.append(func)
+        for loader in settings.TEMPLATE_LOADERS:
+            loaders.append(find_template_loader(loader))
         template_source_loaders = tuple(loaders)
     for loader in template_source_loaders:
         try:
@@ -78,8 +113,10 @@
     Returns a compiled Template object for the given template name,
     handling template inheritance recursively.
     """
-    source, origin = find_template_source(template_name)
-    template = get_template_from_string(source, origin, template_name)
+    template, origin = find_template(template_name)
+    if not hasattr(template, 'render'):
+        # template needs to be compiled
+        template = get_template_from_string(template, origin, template_name)
     return template
 
 def get_template_from_string(source, origin=None, name=None):
Index: tests/regressiontests/test_client_regress/models.py
===================================================================
--- tests/regressiontests/test_client_regress/models.py	(revision 11374)
+++ tests/regressiontests/test_client_regress/models.py	(working copy)
@@ -10,6 +10,7 @@
 from django.core.urlresolvers import reverse
 from django.core.exceptions import SuspiciousOperation
 from django.template import TemplateDoesNotExist, TemplateSyntaxError, Context
+from django.template.loader import find_template_loader
 
 class AssertContainsTests(TestCase):
     def setUp(self):
@@ -436,6 +437,11 @@
 
 class TemplateExceptionTests(TestCase):
     def setUp(self):
+        # Reset the loaders so they don't try to render cached templates.
+        for loader in settings.TEMPLATE_LOADERS:
+            loader = find_template_loader(loader)
+            if hasattr(loader, 'reset'):
+                loader.reset()
         self.old_templates = settings.TEMPLATE_DIRS
         settings.TEMPLATE_DIRS = ()
 
Index: tests/regressiontests/templates/tests.py
===================================================================
--- tests/regressiontests/templates/tests.py	(revision 11374)
+++ tests/regressiontests/templates/tests.py	(working copy)
@@ -105,8 +105,8 @@
                 # Fix expected sources so they are normcased and abspathed
                 expected_sources = [os.path.normcase(os.path.abspath(s)) for s in expected_sources]
             # Test the two loaders (app_directores and filesystem).
-            func1 = lambda p, t: list(app_directories.get_template_sources(p, t))
-            func2 = lambda p, t: list(filesystem.get_template_sources(p, t))
+            func1 = lambda p, t: list(app_directories.loader.get_template_sources(p, t))
+            func2 = lambda p, t: list(filesystem.loader.get_template_sources(p, t))
             for func in (func1, func2):
                 if isinstance(expected_sources, list):
                     self.assertEqual(func(path, template_dirs), expected_sources)
@@ -197,8 +197,11 @@
             except KeyError:
                 raise template.TemplateDoesNotExist, template_name
 
+        from django.template.loaders.cached import Loader
+        cache_loader = Loader((test_template_loader,))
+
         old_template_loaders = loader.template_source_loaders
-        loader.template_source_loaders = [test_template_loader]
+        loader.template_source_loaders = [cache_loader]
 
         failures = []
         tests = template_tests.items()
@@ -231,20 +234,22 @@
             for invalid_str, result in [('', normal_string_result),
                                         (expected_invalid_str, invalid_string_result)]:
                 settings.TEMPLATE_STRING_IF_INVALID = invalid_str
-                try:
-                    test_template = loader.get_template(name)
-                    output = self.render(test_template, vals)
-                except ContextStackException:
-                    failures.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Context stack was left imbalanced" % (invalid_str, name))
-                    continue
-                except Exception:
-                    exc_type, exc_value, exc_tb = sys.exc_info()
-                    if exc_type != result:
-                        tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb))
-                        failures.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Got %s, exception: %s\n%s" % (invalid_str, name, exc_type, exc_value, tb))
-                    continue
-                if output != result:
-                    failures.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Expected %r, got %r" % (invalid_str, name, result, output))
+                for cached in (False, True):
+                    try:
+                        test_template = loader.get_template(name)
+                        output = self.render(test_template, vals)
+                    except ContextStackException:
+                        failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Context stack was left imbalanced" % (cached, invalid_str, name))
+                        continue
+                    except Exception:
+                        exc_type, exc_value, exc_tb = sys.exc_info()
+                        if exc_type != result:
+                            tb = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_tb))
+                            failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Got %s, exception: %s\n%s" % (cached, invalid_str, name, exc_type, exc_value, tb))
+                        continue
+                    if output != result:
+                        failures.append("Template test (Cached='%s', TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Expected %r, got %r" % (cached, invalid_str, name, result, output))
+                cache_loader.reset()
 
             if 'LANGUAGE_CODE' in vals[1]:
                 deactivate()
