Skip to content
Myr

autoescaping is separate from finalize now and Markup is completely ignored if the environment is not in autoescape mode

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 083ae16 · Browse files · 10 files+395 added−145 removed
This commit

State

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

Diff stats

10 files+395 added−145 removed

  • other:+395 added−145 removed

10 files+395 added−145 removed

modified:docs/conf.py+4 added-4 removed
21 unmodified lines
22# ---------------------2324# Add any Sphinx extension module names here, as strings. They can be extensions25# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.26#extensions = []26extensions = ['sphinx.ext.autodoc']2728# Add any paths that contain templates here, relative to this directory.29templates_path = ['_templates']30
35 unmodified lines
66# output. They are ignored by default.67#show_authors = False6869# The name of the Pygments (syntax highlighting) style to use.70pygments_style = 'sphinx'70pygments_style = 'autumn'717273# Options for HTML output74# -----------------------
44 unmodified lines
119# Options for LaTeX output120# ------------------------121122# The paper size ('letter' or 'a4').123#latex_paper_size = 'letter'123latex_paper_size = 'a4'124125# The font size ('10pt', '11pt' or '12pt').126#latex_font_size = '10pt'127
3 unmodified lines
131 ('index', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', 'manual'),132]133134# Additional stuff for the LaTeX preamble.135#latex_preamble = ''135latex_preamble = ''136137# Documents to append as an appendix to all manuals.138#latex_appendices = []139
2 unmodified lines
modified:docs/index.rst+4 added-5 removed
1.. Jinja2 documentation master file, created by sphinx-quickstart on Sun Apr 27 21:42:41 2008.2 You can adapt this file completely to your liking, but it should at least3 contain the root `toctree` directive.41Welcome to Jinja2's documentation!2==================================34Contents:56.. toctree::7 :maxdepth: 289 intro10 api11 templates1213Indices and tables14==================1516* :ref:`genindex`17* :ref:`modindex`18* :ref:`search`19
modified:jinja2/__init__.py+4 added
41 unmodified lines
4243# undefined types44from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined4546# exceptions47from jinja2.exceptions import TemplateError, UndefinedError, \48 TemplateNotFound, TemplateSyntaxError, TemplateAssertionError4950# decorators and public utilities51from jinja2.filters import environmentfilter, contextfilter52from jinja2.utils import Markup, escape, environmentfunction, contextfunction
modified:jinja2/compiler.py+32 added-15 removed
841 unmodified lines
842 self.indent()843 self.pull_locals(macro_frame)844 self.writeline('%s = []' % buf)845 self.blockvisit(node.body, macro_frame)846 if self.environment.autoescape:847 self.writeline('return Markup(concat(%s))' % buf)848 else:846 self.writeline("return Markup(concat(%s))" % buf)849 self.writeline("return concat(%s)" % buf)850 self.outdent()851 self.newline()852 if frame.toplevel:853 if not node.name.startswith('__'):
22 unmodified lines
876 self.indent()877 self.pull_locals(call_frame)878 self.writeline('%s = []' % buf)879 self.blockvisit(node.body, call_frame)880 if self.environment.autoescape:877 self.writeline("return Markup(concat(%s))" % buf)881 self.writeline("return Markup(concat(%s))" % buf)882 else:883 self.writeline('return concat(%s)' % buf)884 self.outdent()885 arg_tuple = ', '.join(repr(x.name) for x in node.args)886 if len(node.args) == 1:887 arg_tuple += ','
44 unmodified lines
932 if self.has_known_extends and frame.toplevel:933 return934935 self.newline(node)930 if self.environment.finalize is unicode:931 finalizer = 'unicode'932 have_finalizer = False933 else:934 finalizer = 'environment.finalize'935 have_finalizer = True936937 # if we are in the toplevel scope and there was already an extends938 # statement we have to add a check that disables our yield(s) here939 # so that they don't appear in the output.
31 unmodified lines
971 self.write(val + ', ')972 else:973 if frame.buffer is None:974 self.writeline('yield ')975 close = 1976 if self.environment.autoescape:975 self.write(finalizer + '(')977 self.write('escape(')978 else:979 self.write('unicode(')980 if self.environment.finalize is not None:981 self.write('environment.finalize(')982 close += 1983 self.visit(item, frame)977 self.write(')')984 self.write(')' * close)985 if frame.buffer is not None:986 self.write(', ')987 if frame.buffer is not None:988 self.write('))')
16 unmodified lines
1005 idx = -11006 self.indent()1007 for argument in arguments:1008 self.newline(argument)1002 if have_finalizer:1003 self.write(finalizer + '(')1009 close = 01010 if self.environment.autoescape:1011 self.write('escape(')1012 close += 11013 if self.environment.finalize is not None:1014 self.write('environment.finalize(')1015 close += 11016 self.visit(argument, frame)1005 if have_finalizer:1006 self.write(')')1017 self.write(')' * close + ',')1007 self.write(',')1018 self.outdent()1019 self.writeline(')')1020 if frame.buffer is not None:1021 self.write(')')
92 unmodified lines
1114 visit_Neg = uaop('-')1115 visit_Not = uaop('not ')1116 del binop, uaop11171118 def visit_Concat(self, node, frame):1119 self.write('join((')1120 for arg in node.nodes:1121 self.visit(arg, frame)1122 self.write(', ')1123 self.write('))')11241125 def visit_Compare(self, node, frame):1126 self.visit(node.expr, frame)1127 for op in node.ops:1128 self.visit(op, frame)
93 unmodified lines
modified:jinja2/environment.py+149 added-69 removed
63 unmodified lines
64 return t656667class Environment(object):68 """The Jinja environment.6970 The core component of Jinja is the `Environment`. It contains68 """The core component of Jinja is the `Environment`. It contains69 important shared variables like configuration, filters, tests,72 globals and others.70 globals and others. Instances of this class may be modified if71 they are not shared and if no template was loaded so far.72 Modifications on environments after the first template was loaded73 will lead to surprising effects and undefined behavior.7475 Here the possible initialization parameters:7677 `block_start_string`78 The string marking the begin of a block. Defaults to ``'{%'``.7980 `block_end_string`81 The string marking the end of a block. Defaults to ``'%}'``.8283 `variable_start_string`84 The string marking the begin of a print statement.85 Defaults to ``'{{'``.8687 `comment_start_string`88 The string marking the begin of a comment. Defaults to ``'{#'``.8990 `comment_end_string`91 The string marking the end of a comment. Defaults to ``'#}'``.9293 `line_statement_prefix`94 If given and a string, this will be used as prefix for line based95 statements.9697 `trim_blocks`98 If this is set to ``True`` the first newline after a block is99 removed (block, not variable tag!). Defaults to `False`.100101 `extensions`102 List of Jinja extensions to use. This can either be import paths103 as strings or extension classes.104105 `optimized`106 should the optimizer be enabled? Default is `True`.107108 `undefined`109 :class:`Undefined` or a subclass of it that is used to represent110 undefined values in the template.111112 `finalize`113 A callable that finalizes the variable. Per default no finalizing114 is applied.115116 `autoescape`117 If set to true the XML/HTML autoescaping feature is enabled.118119 `loader`120 The template loader for this environment.121 """122123 #: if this environment is sandboxed. Modifying this variable won't make124 #: the environment sandboxed though. For a real sandboxed environment
15 unmodified lines
140 trim_blocks=False,141 extensions=(),142 optimized=True,143 undefined=Undefined,96 finalize=unicode,144 finalize=None,145 autoescape=False,146 loader=None):147 # !!Important notice!!148 # The constructor accepts quite a few arguments that should be149 # passed by keyword rather than position. However it's important to
3 unmodified lines
153 # - unittests154 # If parameter changes are required only add parameters at the end155 # and don't change the arguments (or the defaults!) of the arguments156 # up to (but excluding) loader.108 """Here the possible initialization parameters:157110 ========================= ============================================111 `block_start_string` the string marking the begin of a block.112 this defaults to ``'{%'``.113 `block_end_string` the string marking the end of a block.114 defaults to ``'%}'``.115 `variable_start_string` the string marking the begin of a print116 statement. defaults to ``'{{'``.117 `comment_start_string` the string marking the begin of a118 comment. defaults to ``'{#'``.119 `comment_end_string` the string marking the end of a comment.120 defaults to ``'#}'``.121 `line_statement_prefix` If given and a string, this will be used as122 prefix for line based statements. See the123 documentation for more details.124 `trim_blocks` If this is set to ``True`` the first newline125 after a block is removed (block, not126 variable tag!). Defaults to ``False``.127 `extensions` List of Jinja extensions to use.128 `optimized` should the optimizer be enabled? Default is129 ``True``.130 `undefined` a subclass of `Undefined` that is used to131 represent undefined variables.132 `finalize` A callable that finalizes the variable. Per133 default this is `unicode`, other useful134 builtin finalizers are `escape`.135 `loader` the loader which should be used.136 ========================= ============================================137 """138158 # 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 != \
13 unmodified lines
175 # runtime information176 self.undefined = undefined177 self.optimized = optimized178 self.finalize = finalize179 self.autoescape = autoescape180181 # defaults182 self.filters = DEFAULT_FILTERS.copy()183 self.tests = DEFAULT_TESTS.copy()
22 unmodified lines
206 except (TypeError, LookupError):207 return self.undefined(obj=obj, name=argument)208209 def parse(self, source, name=None):190 """Parse the sourcecode and return the abstract syntax tree. This tree191 of nodes is used by the compiler to convert the template into192 executable source- or bytecode.210 """Parse the sourcecode and return the abstract syntax tree. This211 tree of nodes is used by the compiler to convert the template into212 executable source- or bytecode. This is useful for debugging or to213 extract information from templates.214 """215 return Parser(self, source, name).parse()216217 def lex(self, source, name=None):197 """Lex the given sourcecode and return a generator that yields tokens.198 The stream returned is not usable for Jinja but can be used if199 Jinja templates should be processed by other tools (for example200 syntax highlighting etc)201202 The tuples are returned in the form ``(lineno, token, value)``.218 """Lex the given sourcecode and return a generator that yields219 tokens as tuples in the form ``(lineno, token_type, value)``.220 """221 return self.lexer.tokeniter(source, name)222223 def compile(self, source, name=None, filename=None, globals=None,224 raw=False):208 """Compile a node or source. The name is the load name of the209 template after it was joined using `join_path` if necessary,210 filename is the estimated filename of the template on the file211 system. If the template came from a database or memory this212 can be omitted.225 """Compile a node or template source code. The `name` parameter is226 the load name of the template after it was joined using227 :meth:`join_path` if necessary, not the filename on the file system.228 the `filename` parameter is the estimated filename of the template on229 the file system. If the template came from a database or memory this230 can be omitted. The `globals` parameter can be used to provide extra231 variables at compile time for the template. In the future the232 optimizer will be able to evaluate parts of the template at compile233 time based on those variables.234235 The return value of this method is a python code object. If the `raw`236 parameter is `True` the return value will be a string with python237 code equivalent to the bytecode returned otherwise. This method is238 mainly used internally.239 """240 if isinstance(source, basestring):241 source = self.parse(source, name)242 if self.optimized:
8 unmodified lines
251 return compile(source, filename, 'exec')252253 def join_path(self, template, parent):254 """Join a template with the parent. By default all the lookups are229 relative to the loader root, but if the paths should be relative this230 function can be used to calculate the real filename."""255 relative to the loader root so this method returns the `template`256 parameter unchanged, but if the paths should be relative to the257 parent template, this function can be used to calculate the real258 template name.259260 Subclasses may override this method and implement template path261 joining here.262 """263 return template264265 def get_template(self, name, parent=None, globals=None):234 """Load a template."""266 """Load a template from the loader. If a loader is configured this267 method ask the loader for the template and returns a :class:`Template`.268 If the `parent` parameter is not `None`, :meth:`join_path` is called269 to get the real template name before loading.270271 The `globals` parameter can be used to provide compile-time globals.272 In the future this will allow the optimizer to render parts of the273 templates at compile-time.274275 If the template does not exist a :exc:`TemplateNotFound` exception is276 raised.277 """278 if self.loader is None:279 raise TypeError('no loader for this environment specified')280 if parent is not None:281 name = self.join_path(name, parent)282 return self.loader.load(self, name, self.make_globals(globals))283284 def from_string(self, source, globals=None, template_class=None):242 """Load a template from a string."""285 """Load a template from a string. This parses the source given and286 returns a :class:`Template` object.287 """288 globals = self.make_globals(globals)289 return template_from_code(self, self.compile(source, globals=globals),290 globals, None, template_class)291
7 unmodified lines
299class Template(object):300 """The central template object. This class represents a compiled template301 and is used to evaluate it.302258 Normally the template object is generated from an `Environment` but it259 also has a constructor that makes it possible to create a template303 Normally the template object is generated from an :class:`Environment` but304 it also has a constructor that makes it possible to create a template305 instance directly using the constructor. It takes the same arguments as306 the environment constructor but it's not possible to specify a loader.307308 Every template object has a few methods and members that are guaranteed
29 unmodified lines
338 trim_blocks=False,339 extensions=(),340 optimized=True,341 undefined=Undefined,297 finalize=unicode):342 finalize=None,343 autoescape=False):344 env = get_spontaneous_environment(345 block_start_string, block_end_string, variable_start_string,346 variable_end_string, comment_start_string, comment_end_string,347 line_statement_prefix, trim_blocks, tuple(extensions), optimized,302 undefined, finalize)348 undefined, finalize, autoescape)349 return env.from_string(source, template_class=cls)350351 def render(self, *args, **kwargs):306 """Render the template into a string."""352 """This method accepts the same arguments as the `dict` constructor:353 A dict, a dict subclass or some keyword arguments. If no arguments354 are given the context will be empty. These two calls do the same::355356 template.render(knights='that say nih')357 template.render({'knights': 'that say nih'})358359 This will return the rendered template as unicode string.360 """361 try:362 return concat(self.generate(*args, **kwargs))363 except:364 # hide the `generate` frame365 exc_type, exc_value, tb = sys.exc_info()366 raise exc_type, exc_value, tb.tb_next367368 def stream(self, *args, **kwargs):315 """Return a `TemplateStream` that generates the template."""369 """Works exactly like :meth:`generate` but returns a370 :class:`TemplateStream`.371 """372 try:373 return TemplateStream(self.generate(*args, **kwargs))374 except:375 # hide the `generate` frame376 exc_type, exc_value, tb = sys.exc_info()377 raise exc_type, exc_value, tb.tb_next378379 def generate(self, *args, **kwargs):324 """Return a generator that generates the template."""380 """For very large templates it can be useful to not render the whole381 template at once but evaluate each statement after another and yield382 piece for piece. This method basically does exactly that and returns383 a generator that yields one item after another as unicode strings.384385 It accepts the same arguments as :meth:`render`.386 """387 # assemble the context388 context = dict(*args, **kwargs)389390 # if the environment is using the optimizer locals may never
34 unmodified lines
425 return TemplateContext(self.environment, parent, self.name,426 self.blocks)427428 def include(self, vars=None):367 """Include this template. When passed a template context or dict368 the template is evaluated in that context and an `IncludedTemplate`369 object is returned. This object then exposes all the exported370 variables as attributes and renders the contents of the template371 when converted to unicode.429 """Some templates may export macros or other variables. It's possible430 to access those variables by "including" the template. This is mainly431 used internally but may also be useful on the Python layer. If passed432 a context, the template is evaluated in it, otherwise an empty context433 with just the globals is used.434435 The return value is an included template object. Converting it to436 unicode returns the rendered contents of the template, the exported437 variables are accessable via the attribute syntax.438439 This example shows how it can be used:440441 >>> t = Template('{% say_hello(name) %}Hello {{ name }}!{% endmacro %}42')442 >>> i = t.include()443 >>> unicode(i)444 u'42'445 >>> i.say_hello('John')446 u'Hello John!'447 """448 if isinstance(vars, TemplateContext):449 context = TemplateContext(self.environment, vars.parent,450 self.name, self.blocks)
56 unmodified lines
507 return '<%s %s>' % (self.__class__.__name__, name)508509510class TemplateStream(object):436 """This class wraps a generator returned from `Template.generate` so that437 it's possible to buffer multiple elements so that it's possible to return438 them from a WSGI application which flushes after each iteration.511 """A template stream works pretty much like an ordinary python generator512 but it can buffer multiple items to reduce the number of total iterations.513 Per default the output is unbuffered which means that for every unbuffered514 instruction in the template one unicode string is yielded.515516 If buffering is enabled with a buffer size of 5, five items are combined517 into a new unicode string. This is mainly useful if you are streaming518 big templates to a client via WSGI which flushes after each iteration.519 """520521 def __init__(self, gen):522 self._gen = gen
5 unmodified lines
528 self._next = self._gen.next529 self.buffered = False530531 def enable_buffering(self, size=5):452 """Enable buffering. Buffer `size` items before yielding them."""532 """Enable buffering. Buffer `size` items before yielding them."""533 if size <= 1:534 raise ValueError('buffer size too small')535536 def generator():
30 unmodified lines
modified:jinja2/exceptions.py+3 added-5 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~56 Jinja exceptions.78 :copyright: 2007 by Armin Ronacher.8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112
1 unmodified line
14 """Baseclass for all template errors."""151617class UndefinedError(TemplateError):18 """Raised if a template tries to operate on `Undefined`."""18 """Raised if a template tries to operate on :class:`Undefined`."""192021class TemplateNotFound(IOError, LookupError, TemplateError):22 """Raised if a template does not exist."""
20 unmodified lines
43 """444546class TemplateRuntimeError(TemplateError):47 """Raised by the template engine if a tag encountered an error when48 rendering.49 """47 """A runtime error."""
modified:jinja2/ext.py+2 added-2 removed
14 unmodified lines
15from jinja2.environment import get_spontaneous_environment16from jinja2.runtime import Undefined, concat17from jinja2.parser import statement_end_tokens18from jinja2.exceptions import TemplateAssertionError19from jinja2.utils import import_string19from jinja2.utils import import_string, Markup202122# the only real useful gettext functions for a Jinja template. Note23# that ugettext must be assigned to gettext as Jinja doesn't support
261 unmodified lines
285 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),286 tuple(extensions),287 # fill with defaults so that environments are shared288 # with other spontaneus environments.289 True, Undefined, unicode289 True, Undefined, None, False290 )291292 node = environment.parse(fileobj.read().decode(encoding))293 for lineno, func, message in extract_from_ast(node, keywords):
1 unmodified line
modified:jinja2/filters.py+19 added-15 removed
49 unmodified lines
50 value = value.__html__()51 return escape(unicode(value))525354@environmentfilter54def do_replace(s, old, new, count=None):55def do_replace(environment, s, old, new, count=None):56 """Return a copy of the value with all occurrences of a substring57 replaced with a new one. The first argument is the substring58 that should be replaced, the second is the replacement string.59 If the optional third argument ``count`` is given, only the first
8 unmodified lines
68 -> d'oh, d'oh, aaargh69 """70 if count is None:71 count = -172 if not environment.autoescape:73 return unicode(s).replace(unicode(old), unicode(new), count)74 if hasattr(old, '__html__') or hasattr(new, '__html__') and \75 not hasattr(s, '__html__'):76 s = escape(s)77 else:
10 unmodified lines
88 """Convert a value to lowercase."""89 return soft_unicode(s).lower()909189def do_xmlattr(d, autospace=False):92@environmentfilter93def do_xmlattr(_environment, *args, **kwargs):94 """Create an SGML/XML attribute string based on the items in a dict.95 All values that are neither `none` nor `undefined` are automatically96 escaped:97
12 unmodified lines
110 ...111 </ul>112113 As you can see it automatically prepends a space in front of the item110 if the filter returned something. You can disable this by passing111 `false` as only argument to the filter.114 if the filter returned something.115 """113 if not hasattr(d, 'iteritems'):114 raise TypeError('a dict is required')115 result = []116 for key, value in d.iteritems():117 if value is not None and not isinstance(value, Undefined):118 result.append(u'%s="%s"' % (escape(key), escape(value)))116 rv = u' '.join(117 u'%s="%s"' % (escape(key), escape(value))121 for key, value in d.iteritems()118 for key, value in dict(*args, **kwargs).iteritems()119 if value is not None and not isinstance(value, Undefined)120 )124 if autospace:125 rv = ' ' + rv126 return Markup(rv)121 if rv:122 rv = u' ' + rv123 if _environment.autoescape:124 rv = Markup(rv)125 return rv126127128def do_capitalize(s):129 """Capitalize a value. The first character will be uppercase, all others
65 unmodified lines
195 return default_value196 return value197198199@environmentfilter200def do_join(value, d=u''):200def do_join(environment, value, d=u''):201 """Return a string which is the concatenation of the strings in the202 sequence. The separator between elements is an empty string per203 default, you can define ith with the optional parameter:204
4 unmodified lines
209210 {{ [1, 2, 3]|join }}211 -> 123212 """213 # no automatic escaping? joining is a lot eaiser then214 if not environment.autoescape:215 return unicode(d).join(imap(unicode, value))216217 # if the delimiter doesn't have an html representation we check218 # if any of the items has. If yes we do a coercion to Markup219 if not hasattr(d, '__html__'):220 value = list(value)
424 unmodified lines
modified:jinja2/loaders.py+114 added-21 removed
29 unmodified lines
303132class BaseLoader(object):33 """Baseclass for all loaders. Subclass this and override `get_source` to34 implement a custom loading mechanism.34 implement a custom loading mechanism. The environment provides a35 `get_template` method that calls the loader's `load` method to get the36 :class:`Template` object.3736 The environment provides a `get_template` method that will automatically37 call the loader bound to an environment.38 A very basic example for a loader that looks up templates on the file39 system could look like this::4041 from jinja2 import BaseLoader, TemplateNotFound42 from os.path import join, exists, getmtime4344 class MyLoader(BaseLoader):4546 def __init__(self, path, cache_size=50, auto_reload=True):47 BaseLoader.__init__(self, cache_size, auto_reload)48 self.path = path4950 def get_source(self, environment, template):51 path = join(self.path, template)52 if not exists(path):53 raise TemplateNotFound(template)54 mtime = getmtime(path)55 with file(path) as f:56 source = f.read().decode('utf-8')57 return source, path, lambda: mtime != getmtime(path)58 """5960 def __init__(self, cache_size=50, auto_reload=True):61 if cache_size == 0:
24 unmodified lines
86 """87 raise TemplateNotFound(template)8889 def load(self, environment, name, globals=None):70 """Loads a template. This method should not be overriden by71 subclasses unless `get_source` doesn't provide enough flexibility.90 """Loads a template. This method looks up the template in the cache91 or loads one by calling :meth:`get_source`. Subclasses should not92 override this method as loaders working on collections of other93 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)94 will not call this method but `get_source` directly.95 """96 if globals is None:97 globals = {}98
11 unmodified lines
110 return template111112113class FileSystemLoader(BaseLoader):91 """Loads templates from the file system."""114 """Loads templates from the file system. This loader can find templates115 in folders on the file system and is the preferred way to load them.116117 The loader takes the path to the templates as string, or if multiple118 locations are wanted a list of them which is then looked up in the119 given order:120121 >>> loader = FileSystemLoader('/path/to/templates')122 >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])123124 Per default the template encoding is ``'utf-8'`` which can be changed125 by setting the `encoding` parameter to something else.126 """127128 def __init__(self, searchpath, encoding='utf-8', cache_size=50,129 auto_reload=True):130 BaseLoader.__init__(self, cache_size, auto_reload)131 if isinstance(searchpath, basestring):132 searchpath = [searchpath]98 self.searchpath = searchpath133 self.searchpath = list(searchpath)134 self.encoding = encoding135136 def get_source(self, environment, template):137 pieces = split_template_path(template)
11 unmodified lines
149 raise TemplateNotFound(template)150151152class PackageLoader(BaseLoader):118 """Load templates from python eggs."""153 """Load templates from python eggs or packages. It is constructed with154 the name of the python package and the path to the templates in that155 package:156157 >>> loader = PackageLoader('mypackage', 'views')158159 If the package path is not given, ``'templates'`` is assumed.160161 Per default the template encoding is ``'utf-8'`` which can be changed162 by setting the `encoding` parameter to something else. Due to the nature163 of eggs it's only possible to reload templates if the package was loaded164 from the file system and not a zip file.165 """166120 def __init__(self, package_name, package_path, charset='utf-8',121 cache_size=50, auto_reload=True):167 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)123 import pkg_resources124 self._pkg = pkg_resources125 self.package_name = package_name170 from pkg_resources import DefaultProvider, ResourceManager, get_provider171 provider = get_provider(package_name)172 self.encoding = encoding173 self.manager = ResourceManager()174 self.filesystem_bound = isinstance(provider, DefaultProvider)175 self.provider = provider176 self.package_path = package_path177178 def get_source(self, environment, template):179 pieces = split_template_path(template)130 path = '/'.join((self.package_path,) + tuple(pieces))131 if not self._pkg.resource_exists(self.package_name, path):180 p = '/'.join((self.package_path,) + tuple(pieces))181 if not self.provider.has_resource(p):182 raise TemplateNotFound(template)133 return self._pkg.resource_string(self.package_name, path), None, None183184 filename = uptodate = None185 if self.filesystem_bound:186 filename = self.provider.get_resource_filename(self.manager, p)187 mtime = path.getmtime(filename)188 def uptodate():189 return path.getmtime(filename) != mtime190191 source = self.provider.get_resource_string(self.manager, p)192 return source.decode(self.encoding), filename, uptodate193194195class DictLoader(BaseLoader):137 """Loads a template from a python dict. Used for unittests mostly."""196 """Loads a template from a python dict. It's passed a dict of unicode197 strings bound to template names. This loader is useful for unittesting:198199 >>> loader = DictLoader({'index.html': 'source here'})200201 Because auto reloading is rarely useful this is disabled per default.202 """203139 def __init__(self, mapping, cache_size=50):140 BaseLoader.__init__(self, cache_size, False)204 def __init__(self, mapping, cache_size=50, auto_reload=False):205 BaseLoader.__init__(self, cache_size, auto_reload)206 self.mapping = mapping207208 def get_source(self, environment, template):209 if template in self.mapping:145 return self.mapping[template], None, None210 source = self.mapping[template]211 return source, None, lambda: source != self.mapping[template]212 raise TemplateNotFound(template)213214215class FunctionLoader(BaseLoader):216 """A loader that is passed a function which does the loading. The217 function becomes the name of the template passed and has to return either218 an unicode string with the template source, a tuple in the form ``(source,219 filename, uptodatefunc)`` or `None` if the template does not exist.220221 >>> def load_template(name):222 ... if name == 'index.html'223 ... return '...'224 ...225 >>> loader = FunctionLoader(load_template)226227 The `uptodatefunc` is a function that is called if autoreload is enabled228 and has to return `True` if the template is still up to date. For more229 details have a look at :meth:`BaseLoader.get_source` which has the same230 return value.231 """232233 def __init__(self, load_func, cache_size=50, auto_reload=True):234 BaseLoader.__init__(self, cache_size, auto_reload)
11 unmodified lines
246class PrefixLoader(BaseLoader):247 """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 the173 template by a slash.250 template by a slash:251252 >>> loader = PrefixLoader({253 ... 'app1': PackageLoader('mypackage.app1'),254 ... 'app2': PackageLoader('mypackage.app2')255 ... })256257 By loading ``'app1/index.html'`` the file from the app1 package is loaded,258 by loading ``'app2/index.html'`` the file from the second.259 """260261 def __init__(self, mapping, delimiter='/', cache_size=50,262 auto_reload=True):
14 unmodified lines
277 """This loader works like the `PrefixLoader` just that no prefix is278 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.281282 >>> loader = ChoiceLoader([283 ... FileSystemLoader('/path/to/user/templates'),284 ... PackageLoader('myapplication')285 ])286287 This is useful if you want to allow users to override builtin templates288 from a different location.289 """290291 def __init__(self, loaders, cache_size=50, auto_reload=True):292 BaseLoader.__init__(self, cache_size, auto_reload)
9 unmodified lines
modified:jinja2/runtime.py+64 added-9 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from types import FunctionType12from jinja2.utils import Markup, partial13from jinja2.exceptions import UndefinedError12from itertools import chain, imap13from jinja2.utils import Markup, partial, soft_unicode, escape14from jinja2.exceptions import UndefinedError, TemplateRuntimeError151617# these variables are exported to the template runtime18__all__ = ['LoopContext', 'TemplateContext', 'TemplateReference', 'Macro',18 'Markup', 'missing', 'concat']19 'TemplateRuntimeError', 'Markup', 'missing', 'concat', 'escape',20 'markup_join', 'unicode_join']212223# special singleton representing missing values for the runtime24missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
2 unmodified lines
27# concatenate a list of strings and convert them to unicode.28concat = u''.join293031def markup_join(*args):32 """Concatenation that escapes if necessary and converts to unicode."""33 buf = []34 iterator = imap(soft_unicode, args)35 for arg in iterator:36 buf.append(arg)37 if hasattr(arg, '__html__'):38 return Markup(u'').join(chain(buf, iterator))39 return concat(buf)404142def unicode_join(*args):43 """Simple args to unicode conversion and concatenation."""44 return concat(imap(unicode, args))454647class TemplateContext(object):48 """Holds the variables of the local template or of the global one. It's49 not save to use this class outside of the compiled code. For example50 update and other methods will not work as they seem (they don't update
34 unmodified lines
85 raise IndexError()86 except LookupError:87 return self.environment.undefined('there is no parent block '88 'called %r.' % name)89 wrap = self.environment.autoescape and Markup or (lambda x: x)71 render = lambda: Markup(concat(blocks[pos](self)))90 render = lambda: wrap(concat(blocks[pos](self)))91 render.__name__ = render.name = name92 return render9394 def get(self, key, default=None):
46 unmodified lines
141 self.__context = context142143 def __getitem__(self, name):144 func = self.__context.blocks[name][-1]145 wrap = self.__context.environment.autoescape and \146 Markup or (lambda x: x)126 render = lambda: Markup(concat(func(self.__context)))147 render = lambda: wrap(concat(func(self.__context)))148 render.__name__ = render.name = name149 return render150151 def __repr__(self):
137 unmodified lines
289 raise UndefinedError(hint)290291292class Undefined(object):272 """The default undefined implementation. This undefined implementation273 can be printed and iterated over, but every other access will raise a274 `NameError`. Custom undefined classes must subclass this.293 """The default undefined type. This undefined type can be printed and294 iterated over, but every other access will raise an :exc:`UndefinedError`:295296 >>> foo = Undefined(name='foo')297 >>> str(foo)298 ''299 >>> not foo300 True301 >>> foo + 42302 Traceback (most recent call last):303 ...304 jinja2.exceptions.UndefinedError: 'foo' is undefined305 """306 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name')307308 def __init__(self, hint=None, obj=None, name=None):
27 unmodified lines
336 return False337338339class DebugUndefined(Undefined):310 """An undefined that returns the debug info when printed."""340 """An undefined that returns the debug info when printed.341342 >>> foo = DebugUndefined(name='foo')343 >>> str(foo)344 '{{ foo }}'345 >>> not foo346 True347 >>> foo + 42348 Traceback (most recent call last):349 ...350 jinja2.exceptions.UndefinedError: 'foo' is undefined351 """352 __slots__ = ()353354 def __unicode__(self):355 if self._undefined_hint is None:
9 unmodified lines
365class StrictUndefined(Undefined):366 """An undefined that barks on print and iteration as well as boolean367 tests and all kinds of comparisons. In other words: you can do nothing368 with it except checking if it's defined using the `defined` test.369370 >>> foo = StrictUndefined(name='foo')371 >>> str(foo)372 Traceback (most recent call last):373 ...374 jinja2.exceptions.UndefinedError: 'foo' is undefined375 >>> not foo376 Traceback (most recent call last):377 ...378 jinja2.exceptions.UndefinedError: 'foo' is undefined379 >>> foo + 42380 Traceback (most recent call last):381 ...382 jinja2.exceptions.UndefinedError: 'foo' is undefined383 """384 __slots__ = ()385 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \386 fail_with_undefined_error
5 unmodified lines