Skip to content
Myr

moved caching from loaders to environment and added environment overlays

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent d84ec46 · Browse files · 13 files+426 added−149 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+426 added−149 removed

  • tests:+2 added−2 removed
  • other:+424 added−147 removed

13 files+426 added−149 removed

modified:docs/api.rst+166 added-23 removed
46 unmodified lines
47High Level API48--------------4950.. autoclass:: jinja2.environment.Environment51 :members: from_string, get_template, join_path51 :members: from_string, get_template, join_path, overlay5253 .. attribute:: shared5455 If a template was created by using the :class:`Template` constructor
10 unmodified lines
6667 .. attribute:: filters6869 A dict of filters for this environment. As long as no template was70 loaded it's safe to add new filters or remove old.70 loaded it's safe to add new filters or remove old. For custom filters71 see :ref:`writing-filters`.7273 .. attribute:: tests7475 A dict of test funcitons for this environment. As long as no75 template way loaded it's safe to modify this dict.76 template way loaded it's safe to modify this dict. For custom tests77 see :ref:`writing-tests`.7879 .. attribute:: globals8081 A dict of global variables. These variables are always available82 in a template and (if the optimizer is enabled) may not be83 override by templates. As long as no template was loaded it's safe82 to modify this dict.84 to modify this dict. For more details see :ref:`global-namespace`.858687.. autoclass:: jinja2.Template88 :members: render, stream, generate, module8990 .. attribute:: globals9192 foo9394 .. attribute:: name9596 foo979899.. autoclass:: jinja2.environment.TemplateStream100 :members: disable_buffering, enable_buffering101102
16 unmodified lines
119120.. autoclass:: jinja2.runtime.StrictUndefined121122123The Context124-----------125126.. autoclass:: jinja2.runtime.TemplateContext127 :members: super, get, get_exported, get_all128129 .. attribute:: parent130131 A dict of read only, global variables the template looks up. These132 can either come from another :class:`TemplateContext`, from the133 :attr:`Environment.globals` or :attr:`Template.globals`. It must not134 be altered.135136 .. attribute:: vars137138 The template local variables. This list contains environment and139 context functions from the :attr:`parent` scope as well as local140 modifications and exported variables from the template. The template141 will modify this dict during template evaluation but filters and142 context functions are not allowed to modify it.143144 .. attribute:: environment145146 The environment that loaded the template.147148 .. attribute:: exported_vars149150 This set contains all the names the template exports. The values for151 the names are in the :attr:`vars` dict. In order to get a copy of the152 exported variables as dict, :meth:`get_exported` can be used.153154 .. attribute:: name155156 The load name of the template owning this context.157158 .. attribute:: blocks159160 A dict with the current mapping of blocks in the template. The keys161 in this dict are the names of the blocks, and the values a list of162 blocks registered. The last item in each list is the current active163 block (latest in the inheritance chain).164165166Loaders167-------168169Loaders are responsible for loading templates from a resource such as the117file system and for keeping the compiled modules in memory. These work like118Python's `sys.modules` which keeps the imported templates in memory. Unlike119`sys.modules` however this cache is limited in size by default and templates120are automatically reloaded. Each loader that extends :class:`BaseLoader`121supports this caching and accepts two parameters to configure it:170file system. The environment will keep the compiled modules in memory like171Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in172size by default and templates are automatically reloaded.173123`cache_size`124 The size of the cache. Per default this is ``50`` which means that if125 more than 50 templates are loaded the loader will clean out the least126 recently used template. If the cache size is set to ``0`` templates are127 recompiled all the time, if the cache size is ``-1`` the cache will not128 be cleaned.129130`auto_reload`131 Some loaders load templates from locations where the template sources132 may change (ie: file system or database). If `auto_reload` is set to133 `True` (default) every time a template is requested the loader checks134 if the source changed and if yes, it will reload the template. For135 higher performance it's possible to disable that.136174.. autoclass:: jinja2.loaders.FileSystemLoader175176.. autoclass:: jinja2.loaders.PackageLoader177
47 unmodified lines
225226.. autoclass:: jinja2.exceptions.TemplateSyntaxError227228.. autoclass:: jinja2.exceptions.TemplateAssertionError229230231.. _writing-filters:232233Custom Filters234--------------235236Custom filters are just regular Python functions that take the left side of237the filter as first argument and the the arguments passed to the filter as238extra arguments or keyword arguments.239240For example in the filter ``{{ 42|myfilter(23) }}`` the function would be241called with ``myfilter(42, 23)``. Here for example a simple filter that can242be applied to datetime objects to format them::243244 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):245 return value.strftime(format)246247You can register it on the template environment by updating the248:attr:`~Environment.filters` dict on the environment::249250 environment.filters['datetimeformat'] = datetimeformat251252Inside the template it can then be used as follows:253254.. sourcecode:: jinja255256 written on: {{ article.pub_date|datetimeformat }}257 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}258259Filters can also be passed the current template context or environment. This260is useful if a filters wants to return an undefined value or check the current261:attr:`~Environment.autoescape` setting. For this purpose two decorators262exist: :func:`environmentfilter` and :func:`contextfilter`.263264Here a small example filter that breaks a text into HTML line breaks and265paragraphs and marks the return value as safe HTML string if autoescaping is266enabled::267268 import re269 from jinja2 import environmentfilter, Markup, escape270271 _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')272273 @environmentfilter274 def nl2br(environment, value):275 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')276 for p in _paragraph_re.split(escape(value)))277 if environment.autoescape:278 result = Markup(result)279 return result280281Context filters work the same just that the first argument is the current282active :class:`TemplateContext` rather then the environment.283284285.. _writing-tests:286287Custom Tests288------------289290Tests work like filters just that there is no way for a filter to get access291to the environment or context and that they can't be chained. The return292value of a filter should be `True` or `False`. The purpose of a filter is to293give the template designers the possibility to perform type and conformability294checks.295296Here a simple filter that checks if a variable is a prime number::297298 import math299300 def is_prime(n):301 if n == 2:302 return True303 for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1):304 if n % i == 0:305 return False306 return True307 308309You can register it on the template environment by updating the310:attr:`~Environment.tests` dict on the environment::311312 environment.tests['prime'] = is_prime313314A template designer can then use the test like this:315316.. sourcecode:: jinja317318 {% if 42 is prime %}319 42 is a prime number320 {% else %}321 42 is not a prime number322 {% endif %}323324325.. _global-namespace:326327The Global Namespace328--------------------329330Variables stored in the :attr:`Environment.globals` or :attr:`Template.globals`331dicts are special as they are available for imported templates too and will be332used by the optimizer in future releases to evaluates parts of the template at333compile time. This is the place where you can put variables and functions334that should be available all the time.
modified:docs/conf.py+1 added-1 removed
135 unmodified lines
136\usepackage{palatino}137\definecolor{TitleColor}{rgb}{0.7,0,0}138\definecolor{InnerLinkColor}{rgb}{0.7,0,0}139\definecolor{OuterLinkColor}{rgb}{0.8,0,0}140\definecolor{VerbatimColor}{rgb}{0.98,0.98,0.98}140\definecolor{VerbatimColor}{rgb}{0.985,0.985,0.985}141\definecolor{VerbatimBorderColor}{rgb}{0.8,0.8,0.8}142'''143144# Documents to append as an appendix to all manuals.
4 unmodified lines
modified:docs/jinjaext.py+1 added-1 removed
41 unmodified lines
42 Name.Attribute: '#686868',43 Name.Tag: 'bold #686868',44 Name.Decorator: '#686868',4546 String: '#BE9B5D',46 String: '#AA891C',47 Number: '#444444',4849 Generic.Heading: 'bold #000080',50 Generic.Subheading: 'bold #800080',
72 unmodified lines
modified:docs/templates.rst+21 added
780 unmodified lines
781List of Builtin Tests782---------------------783784.. jinjatests::785786787List of Global Functions788------------------------789790The following functions are available in the global scope by default:791792.. function:: range([start,] stop[, step])793794 Return a list containing an arithmetic progression of integers.795 range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.796 When step is given, it specifies the increment (or decrement).797 For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!798 These are exactly the valid indices for a list of 4 elements.799800.. function:: lipsum(n=5, html=True, min=20, max=100)801802 Generates some lorem ipsum for the template. Per default five paragraphs803 with HTML are generated each paragraph between 20 and 100 words. If html804 is disabled regular text is returned. This is useful to generate simple805 contents for layout testing.
modified:jinja2/__init__.py+10 added
48 unmodified lines
4950# decorators and public utilities51from jinja2.filters import environmentfilter, contextfilter52from jinja2.utils import Markup, escape, environmentfunction, contextfunction5354__all__ = [55 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',56 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',57 'ChoiceLoader', 'Undefined', 'DebugUndefined', 'StrictUndefined',58 'TemplateError', 'UndefinedError', 'TemplateNotFound',59 'TemplateSyntaxError', 'TemplateAssertionError', 'environmentfilter',60 'contextfilter', 'Markup', 'escape', 'environmentfunction',61 'contextfunction'62]
modified:jinja2/defaults.py+13 added
11 unmodified lines
12from jinja2.tests import TESTS as DEFAULT_TESTS13from jinja2.utils import generate_lorem_ipsum141516BLOCK_START_STRING = '{%'17BLOCK_END_STRING = '%}'18VARIABLE_START_STRING = '{{'19VARIABLE_END_STRING = '}}'20COMMENT_START_STRING = '{#'21COMMENT_END_STRING = '#}'22LINE_STATEMENT_PREFIX = None232425DEFAULT_NAMESPACE = {26 'range': xrange,27 'lipsum': generate_lorem_ipsum28}293031# export all constants32__all__ = tuple(x for x in locals() if x.isupper())
modified:jinja2/environment.py+147 added-50 removed
7 unmodified lines
8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import sys12from jinja2.defaults import *13from jinja2.lexer import Lexer14from jinja2.parser import Parser15from jinja2.optimizer import optimize16from jinja2.compiler import generate17from jinja2.runtime import Undefined, TemplateContext, concat18from jinja2.debug import translate_exception18from jinja2.utils import import_string, LRUCache, Markup19from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19from jinja2.utils import import_string, LRUCache, Markup, missing202122# for direct template usage we have up to ten living environments23_spontaneous_environments = LRUCache(10)
14 unmodified lines
38 env.shared = True39 return env404142def template_from_code(environment, code, globals, uptodate=None,43 template_class=None):44 """Generate a new template object from code. It's used in the45 template constructor and the loader `load` implementation.42def create_cache(size):43 """Return the cache class for the given size."""44 if size == 0:45 return None46 if size < 0:47 return {}48 return LRUCache(size)495051def load_extensions(environment, extensions):52 """Load the extensions from the list and bind it to the environment.53 Returns a new list of instanciated environments.54 """47 t = object.__new__(template_class or environment.template_class)48 namespace = {49 'environment': environment,50 '__jinja_template__': t51 }52 exec code in namespace53 t.environment = environment54 t.name = namespace['name']55 t.filename = code.co_filename56 t.root_render_func = namespace['root']57 t.blocks = namespace['blocks']58 t.globals = globals55 result = []56 for extension in extensions:57 if isinstance(extension, basestring):58 extension = import_string(extension)59 result.append(extension(environment))60 return result6160 # debug and loader helpers61 t._debug_info = namespace['debug_info']62 t._uptodate = uptodate6264 return t63def _environment_sanity_check(environment):64 """Perform a sanity check on the environment."""65 assert issubclass(environment.undefined, Undefined), 'undefined must ' \66 'be a subclass of undefined because filters depend on it.'67 assert environment.block_start_string != \68 environment.variable_start_string != \69 environment.comment_start_string, 'block, variable and comment ' \70 'start strings must be different'717273class Environment(object):74 """The core component of Jinja is the `Environment`. It contains
48 unmodified lines
123 If set to true the XML/HTML autoescaping feature is enabled.124125 `loader`126 The template loader for this environment.127128 `cache_size`129 The size of the cache. Per default this is ``50`` which means that if130 more than 50 templates are loaded the loader will clean out the least131 recently used template. If the cache size is set to ``0`` templates are132 recompiled all the time, if the cache size is ``-1`` the cache will not133 be cleaned.134135 `auto_reload`136 Some loaders load templates from locations where the template sources137 may change (ie: file system or database). If `auto_reload` is set to138 `True` (default) every time a template is requested the loader checks139 if the source changed and if yes, it will reload the template. For140 higher performance it's possible to disable that.141 """142143 #: if this environment is sandboxed. Modifying this variable won't make144 #: the environment sandboxed though. For a real sandboxed environment145 #: have a look at jinja2.sandbox146 sandboxed = False147148 #: True if the environment is just an overlay149 overlay = False150151 #: shared environments have this set to `True`. A shared environment152 #: must not be modified153 shared = False154155 def __init__(self,133 block_start_string='{%',134 block_end_string='%}',135 variable_start_string='{{',136 variable_end_string='}}',137 comment_start_string='{#',138 comment_end_string='#}',139 line_statement_prefix=None,156 block_start_string=BLOCK_START_STRING,157 block_end_string=BLOCK_END_STRING,158 variable_start_string=VARIABLE_START_STRING,159 variable_end_string=VARIABLE_END_STRING,160 comment_start_string=COMMENT_START_STRING,161 comment_end_string=COMMENT_END_STRING,162 line_statement_prefix=LINE_STATEMENT_PREFIX,163 trim_blocks=False,164 extensions=(),165 optimized=True,166 undefined=Undefined,167 finalize=None,168 autoescape=False,146 loader=None):169 loader=None,170 cache_size=50,171 auto_reload=True):172 # !!Important notice!!173 # The constructor accepts quite a few arguments that should be174 # passed by keyword rather than position. However it's important to175 # not change the order of arguments because it's used at least
1 unmodified line
177 # - spontaneus environments (i18n extension and Template)178 # - unittests179 # If parameter changes are required only add parameters at the end180 # and don't change the arguments (or the defaults!) of the arguments156 # up to (but excluding) loader.181 # existing already.182158 # santity checks159 assert issubclass(undefined, Undefined), 'undefined must be ' \160 'a subclass of undefined because filters depend on it.'161 assert block_start_string != variable_start_string != \162 comment_start_string, 'block, variable and comment ' \163 'start strings must be different'164183 # lexer / parser information184 self.block_start_string = block_start_string185 self.block_end_string = block_end_string186 self.variable_start_string = variable_start_string
15 unmodified lines
202 self.globals = DEFAULT_NAMESPACE.copy()203204 # set the loader provided205 self.loader = loader206 self.cache = create_cache(cache_size)207 self.auto_reload = auto_reload208189 # create lexer190 self.lexer = Lexer(self)191209 # load extensions193 self.extensions = []194 for extension in extensions:195 if isinstance(extension, basestring):196 extension = import_string(extension)197 self.extensions.append(extension(self))210 self.extensions = load_extensions(self, extensions)211212 _environment_sanity_check(self)213214 def overlay(self, block_start_string=missing, block_end_string=missing,215 variable_start_string=missing, variable_end_string=missing,216 comment_start_string=missing, comment_end_string=missing,217 line_statement_prefix=missing, trim_blocks=missing,218 extensions=missing, optimized=missing, undefined=missing,219 finalize=missing, autoescape=missing, loader=missing,220 cache_size=missing, auto_reload=missing):221 """Create a new overlay environment that shares all the data with the222 current environment except of cache and the overriden attributes.223 Extensions cannot be removed for a overlayed environment. A overlayed224 environment automatically gets all the extensions of the environment it225 is linked to plus optional extra extensions.226227 Creating overlays should happen after the initial environment was set228 up completely. Not all attributes are truly linked, some are just229 copied over so modifications on the original environment may not shine230 through.231 """232 args = dict(locals())233 del args['self'], args['cache_size'], args['extensions']234235 rv = object.__new__(self.__class__)236 rv.__dict__.update(self.__dict__)237 rv.overlay = True238 rv.linked_to = self239240 for key, value in args.iteritems():241 if value is not missing:242 setattr(rv, key, value)243244 if cache_size is not missing:245 rv.cache = create_cache(cache_size)246247 rv.extensions = []248 for extension in self.extensions:249 rv.extensions.append(extension.bind(self))250 if extensions is not missing:251 rv.extensions.extend(load_extensions(extensions))252253 _environment_sanity_check(rv)254 return rv255256 @property257 def lexer(self):258 """Return a fresh lexer for the environment."""259 return Lexer(self)260261 def subscribe(self, obj, argument):262 """Get an item or attribute of an object."""263 try:264 return getattr(obj, str(argument))
75 unmodified lines
340 if self.loader is None:341 raise TypeError('no loader for this environment specified')342 if parent is not None:343 name = self.join_path(name, parent)282 return self.loader.load(self, name, self.make_globals(globals))344345 if self.cache is not None:346 template = self.cache.get(name)347 if template is not None and (not self.auto_reload or \348 template.is_up_to_date):349 return template350351 template = self.loader.load(self, name, self.make_globals(globals))352 if self.cache is not None:353 self.cache[name] = template354 return template355356 def from_string(self, source, globals=None, template_class=None):357 """Load a template from a string. This parses the source given and358 returns a :class:`Template` object.359 """360 globals = self.make_globals(globals)361 cls = template_class or self.template_class289 return template_from_code(self, self.compile(source, globals=globals),290 globals, None, template_class)362 return cls.from_code(self, self.compile(source, globals=globals),363 globals, None)364365 def make_globals(self, d):366 """Return a dict for the globals."""367 if d is None:
49 unmodified lines
417 env = get_spontaneous_environment(418 block_start_string, block_end_string, variable_start_string,419 variable_end_string, comment_start_string, comment_end_string,420 line_statement_prefix, trim_blocks, tuple(extensions), optimized,348 undefined, finalize, autoescape)421 undefined, finalize, autoescape, None, 0, False)422 return env.from_string(source, template_class=cls)423424 @classmethod425 def from_code(cls, environment, code, globals, uptodate=None):426 """Creates a template object from compiled code and the globals. This427 is used by the loaders and environment to create a template object.428 """429 t = object.__new__(cls)430 namespace = {431 'environment': environment,432 '__jinja_template__': t433 }434 exec code in namespace435 t.environment = environment436 t.name = namespace['name']437 t.filename = code.co_filename438 t.root_render_func = namespace['root']439 t.blocks = namespace['blocks']440 t.globals = globals441442 # debug and loader helpers443 t._debug_info = namespace['debug_info']444 t._uptodate = uptodate445446 return t447448 def render(self, *args, **kwargs):449 """This method accepts the same arguments as the `dict` constructor:450 A dict, a dict subclass or some keyword arguments. If no arguments451 are given the context will be empty. These two calls do the same::
202 unmodified lines
modified:jinja2/ext.py+18 added-3 removed
24 unmodified lines
25GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')262728class Extension(object):29 """Instances of this class store parser extensions."""29 """Extensions can be used to add extra functionality to the Jinja template30 system at the parser level. This is a supported but currently31 undocumented interface. Custom extensions are bound to an environment but32 may not store environment specific data on `self`. The reason for this is33 that an extension can be bound to another environment (for overlays) by34 creating a copy and reassigning the `environment` attribute.35 """3637 #: if this extension parses this is the list of tags it's listening to.38 tags = set()3940 def __init__(self, environment):41 self.environment = environment4243 def bind(self, environment):44 """Create a copy of this extension bound to another environment."""45 rv = object.__new__(self.__class__)46 rv.__dict__.update(self.__dict__)47 rv.environment = environment48 return rv4950 def parse(self, parser):51 """Called if one of the tags matched."""5253
247 unmodified lines
301 options.get('line_statement_prefix') or None,302 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),303 tuple(extensions),304 # fill with defaults so that environments are shared292 # with other spontaneus environments.293 True, Undefined, None, False305 # with other spontaneus environments. The rest of the306 # arguments are optimizer, undefined, finalize, autoescape,307 # loader, cache size and auto reloading setting308 True, Undefined, None, False, None, 0, False309 )310311 node = environment.parse(fileobj.read().decode(encoding))312 for lineno, func, message in extract_from_ast(node, keywords):
1 unmodified line
modified:jinja2/loaders.py+16 added-40 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 Jinja loader classes.78 XXX: move caching from the loaders to environment.get_template and add9 environment overlays that allow to redefine escaping and other things but10 shared the globals and filter mappings.1112 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15from os import path16from jinja2.exceptions import TemplateNotFound13from jinja2.environment import template_from_code17from jinja2.utils import LRUCache181920def split_template_path(template):
38 unmodified lines
59 source = f.read().decode('utf-8')60 return source, path, lambda: mtime != getmtime(path)61 """6260 def __init__(self, cache_size=50, auto_reload=True):61 if cache_size == 0:62 self.cache = None63 elif cache_size < 0:64 self.cache = {}65 else:66 self.cache = LRUCache(cache_size)67 self.auto_reload = auto_reload6863 def get_source(self, environment, template):64 """Get the template source, filename and reload helper for a template.65 It's passed the environment and template name and has to return a66 tuple in the form ``(source, filename, uptodate)`` or raise a
21 unmodified lines
88 will not call this method but `get_source` directly.89 """90 if globals is None:91 globals = {}9899 if self.cache is not None:100 template = self.cache.get(name)101 if template is not None and (not self.auto_reload or \102 template.is_up_to_date):103 return template10492 source, filename, uptodate = self.get_source(environment, name)93 code = environment.compile(source, name, filename, globals)107 template = template_from_code(environment, code, globals, uptodate)108 if self.cache is not None:109 self.cache[name] = template110 return template94 return environment.template_class.from_code(environment, code,95 globals, uptodate)969798class FileSystemLoader(BaseLoader):99 """Loads templates from the file system. This loader can find templates
9 unmodified lines
109 Per default the template encoding is ``'utf-8'`` which can be changed110 by setting the `encoding` parameter to something else.111 """112128 def __init__(self, searchpath, encoding='utf-8', cache_size=50,129 auto_reload=True):130 BaseLoader.__init__(self, cache_size, auto_reload)113 def __init__(self, searchpath, encoding='utf-8'):114 if isinstance(searchpath, basestring):115 searchpath = [searchpath]116 self.searchpath = list(searchpath)117 self.encoding = encoding
29 unmodified lines
147 from the file system and not a zip file.148 """149150 def __init__(self, package_name, package_path='templates',168 encoding='utf-8', cache_size=50, auto_reload=True):169 BaseLoader.__init__(self, cache_size, auto_reload)151 encoding='utf-8'):152 from pkg_resources import DefaultProvider, ResourceManager, get_provider153 provider = get_provider(package_name)154 self.encoding = encoding155 self.manager = ResourceManager()
26 unmodified lines
182183 Because auto reloading is rarely useful this is disabled per default.184 """185204 def __init__(self, mapping, cache_size=50, auto_reload=False):205 BaseLoader.__init__(self, cache_size, auto_reload)186 def __init__(self, mapping):187 self.mapping = mapping188189 def get_source(self, environment, template):190 if template in self.mapping:
19 unmodified lines
210 details have a look at :meth:`BaseLoader.get_source` which has the same211 return value.212 """213233 def __init__(self, load_func, cache_size=50, auto_reload=True):234 BaseLoader.__init__(self, cache_size, auto_reload)214 def __init__(self, load_func):215 self.load_func = load_func216217 def get_source(self, environment, template):218 rv = self.load_func(template)
5 unmodified lines
224225226class PrefixLoader(BaseLoader):227 """A loader that is passed a dict of loaders where each loader is bound248 to a prefix. The caching is independent of the actual loaders so the249 per loader cache settings are ignored. The prefix is delimited from the250 template by a slash:228 to a prefix. The prefix is delimited from the template by a slash per229 default, which can be changed by setting the `delimiter` argument to230 something else.231232 >>> loader = PrefixLoader({233 ... 'app1': PackageLoader('mypackage.app1'),234 ... 'app2': PackageLoader('mypackage.app2')
2 unmodified lines
237 By loading ``'app1/index.html'`` the file from the app1 package is loaded,238 by loading ``'app2/index.html'`` the file from the second.239 """240261 def __init__(self, mapping, delimiter='/', cache_size=50,262 auto_reload=True):263 BaseLoader.__init__(self, cache_size, auto_reload)241 def __init__(self, mapping, delimiter='/'):242 self.mapping = mapping243 self.delimiter = delimiter244245 def get_source(self, environment, template):
7 unmodified lines
253254class ChoiceLoader(BaseLoader):255 """This loader works like the `PrefixLoader` just that no prefix is256 specified. If a template could not be found by one loader the next one279 is tried. Like for the `PrefixLoader` the cache settings of the actual280 loaders don't matter as the choice loader does the caching.257 is tried.258259 >>> loader = ChoiceLoader([260 ... FileSystemLoader('/path/to/user/templates'),261 ... PackageLoader('myapplication')
2 unmodified lines
264 This is useful if you want to allow users to override builtin templates265 from a different location.266 """267291 def __init__(self, loaders, cache_size=50, auto_reload=True):292 BaseLoader.__init__(self, cache_size, auto_reload)268 def __init__(self, loaders):269 self.loaders = loaders270271 def get_source(self, environment, template):272 for loader in self.loaders:
5 unmodified lines
modified:jinja2/runtime.py+24 added-27 removed
9 unmodified lines
10"""11import sys12from types import FunctionType13from itertools import chain, imap14from jinja2.utils import Markup, partial, soft_unicode, escape14from jinja2.utils import Markup, partial, soft_unicode, escape, missing15from jinja2.exceptions import UndefinedError, TemplateRuntimeError161718# these variables are exported to the template runtime
1 unmodified line
20 'TemplateRuntimeError', 'Markup', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']222324# special singleton representing missing values for the runtime25missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()262724# concatenate a list of strings and convert them to unicode.25# unfortunately there is a bug in python 2.4 and lower that causes26# unicode.join trash the traceback.27try:28 def _test_gen_bug():29 raise TypeError(_test_gen_bug)30 yield None31 u''.join(_test_gen_bug())36except TypeError, e:37 if e.args and e.args[0] is _test_gen_bug:32except TypeError, _error:33 if _error.args and _error.args[0] is _test_gen_bug:34 concat = u''.join35 else:36 def concat(gen):37 try:38 return u''.join(list(gen))39 except:40 exc_type, exc_value, tb = sys.exc_info()41 raise exc_type, exc_value, tb.tb_next46del _test_gen_bug42 del _test_gen_bug, _error434445def markup_join(*args):46 """Concatenation that escapes if necessary and converts to unicode."""
11 unmodified lines
58 return concat(imap(unicode, args))596061class TemplateContext(object):66 """Holds the variables of the local template or of the global one. It's67 not save to use this class outside of the compiled code. For example68 update and other methods will not work as they seem (they don't update69 the exported variables for example).62 """The template context holds the variables of a template. It stores the63 values passed to the template and also the names the template exports.64 Creating instances is neither supported nor useful as it's created65 automatically at various stages of the template evaluation and should not66 be created by hand.6771 The context is immutable. Modifications on `parent` must not happen and72 modifications on `vars` are allowed from generated template code. However73 functions that are passed the template context may not modify the context74 in any way.68 The context is immutable. Modifications on :attr:`parent` **must not**69 happen and modifications on :attr:`vars` are allowed from generated70 template code only. Template filters and global functions marked as71 :func:`contextfunction`\s get the active context passed as first argument72 and are allowed to access the context read-only.7374 The template context supports read only dict operations (`get`,75 `__getitem__`, `__contains__`) however `__getitem__` doesn't fail with76 a `KeyError` but returns an :attr:`Undefined` object.77 """7879 def __init__(self, environment, parent, name, blocks):80 self.parent = parent
30 unmodified lines
111 render.__name__ = render.name = name112 return render113114 def get(self, key, default=None):113 """For dict compatibility"""115 """Returns an item from the template context, if it doesn't exist116 `default` is returned.117 """118 if key in self.vars:119 return self.vars[key]120 if key in self.parent:121 return self.parent[key]
2 unmodified lines
124 def get_exported(self):125 """Get a new dict with the exported variables."""126 return dict((k, self.vars[k]) for k in self.exported_vars)127124 def get_root(self):125 """Return a new dict with all the non local variables."""126 return dict(self.parent)127128 def get_all(self):129 """Return a copy of the complete context as dict."""129 """Return a copy of the complete context as dict including the130 global variables.131 """132 return dict(self.parent, **self.vars)133132 def clone(self):133 """Return a copy of the context without the locals."""134 return self.__class__(self.environment, self.parent,135 self.name, self.blocks)136134 def __contains__(self, name):135 return name in self.vars or name in self.parent136137 def __getitem__(self, key):
268 unmodified lines
modified:jinja2/utils.py+4 added
23 unmodified lines
24)25_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')262728# special singleton representing missing values for the runtime29missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()303132def contextfunction(f):33 """This decorator can be used to mark a callable as context callable. A34 context callable is passed the active context as first argument if it35 was directly stored in the context.
398 unmodified lines
modified:tests/conftest.py+2 added-2 removed
61 unmodified lines
62 except KeyError:63 raise TemplateNotFound(name)646566loader = GlobalLoader(cache_size=0)67simple_env = Environment(trim_blocks=True, loader=loader)66loader = GlobalLoader()67simple_env = Environment(trim_blocks=True, loader=loader, cache_size=0)686970class Module(py.test.collect.Module):71
37 unmodified lines
modified:.hgignore+3 added-2 removed
1^instance$2^instance/3^jinja/.*\.so$4^(build|dist|Jinja\.egg-info)/3^jinja2/.*\.so$4^docs/_.*5^(build|dist|Jinja2\.egg-info)/6\.py[co]$7\.DS_Store$