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
Provenance
- Commit
d134231- Tree
c258b37- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
083ae16
10 files changed+395 added−145 removed
modified:docs/conf.py+4 added-4 removed
21 unmodified lines22 # ---------------------23 24 # 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 = []26+extensions = ['sphinx.ext.autodoc']27 28 # Add any paths that contain templates here, relative to this directory.29 templates_path = ['_templates']30 35 unmodified lines66 # output. They are ignored by default.67 #show_authors = False68 69 # The name of the Pygments (syntax highlighting) style to use.70-pygments_style = 'sphinx'70+pygments_style = 'autumn'71 72 73 # Options for HTML output74 # -----------------------44 unmodified lines119 # Options for LaTeX output120 # ------------------------121 122 # The paper size ('letter' or 'a4').123-#latex_paper_size = 'letter'123+latex_paper_size = 'a4'124 125 # The font size ('10pt', '11pt' or '12pt').126 #latex_font_size = '10pt'127 3 unmodified lines131 ('index', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', 'manual'),132 ]133 134 # Additional stuff for the LaTeX preamble.135-#latex_preamble = ''135+latex_preamble = ''136 137 # Documents to append as an appendix to all manuals.138 #latex_appendices = []139 2 unmodified linesmodified: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.4-1 Welcome to Jinja2's documentation!2 ==================================3 4 Contents:5 6 .. toctree::7 :maxdepth: 28 9+ intro10+ api11+ templates12+13 Indices and tables14 ==================15 16 * :ref:`genindex`17 * :ref:`modindex`18 * :ref:`search`19-modified:jinja2/__init__.py+4 added
41 unmodified lines42 43 # undefined types44 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined45 46+# exceptions47+from jinja2.exceptions import TemplateError, UndefinedError, \48+ TemplateNotFound, TemplateSyntaxError, TemplateAssertionError49+50 # decorators and public utilities51 from jinja2.filters import environmentfilter, contextfilter52 from jinja2.utils import Markup, escape, environmentfunction, contextfunctionmodified:jinja2/compiler.py+32 added-15 removed
841 unmodified lines842 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 lines876 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 lines932 if self.has_known_extends and frame.toplevel:933 return934 935 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 = True936 937 # 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 lines971 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 lines1005 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 lines1114 visit_Neg = uaop('-')1115 visit_Not = uaop('not ')1116 del binop, uaop1117 1118+ 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('))')1124+1125 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 linesmodified:jinja2/environment.py+149 added-69 removed
63 unmodified lines64 return t65 66 67 class Environment(object):68- """The Jinja environment.69-70- 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.74+75+ Here the possible initialization parameters:76+77+ `block_start_string`78+ The string marking the begin of a block. Defaults to ``'{%'``.79+80+ `block_end_string`81+ The string marking the end of a block. Defaults to ``'%}'``.82+83+ `variable_start_string`84+ The string marking the begin of a print statement.85+ Defaults to ``'{{'``.86+87+ `comment_start_string`88+ The string marking the begin of a comment. Defaults to ``'{#'``.89+90+ `comment_end_string`91+ The string marking the end of a comment. Defaults to ``'#}'``.92+93+ `line_statement_prefix`94+ If given and a string, this will be used as prefix for line based95+ statements.96+97+ `trim_blocks`98+ If this is set to ``True`` the first newline after a block is99+ removed (block, not variable tag!). Defaults to `False`.100+101+ `extensions`102+ List of Jinja extensions to use. This can either be import paths103+ as strings or extension classes.104+105+ `optimized`106+ should the optimizer be enabled? Default is `True`.107+108+ `undefined`109+ :class:`Undefined` or a subclass of it that is used to represent110+ undefined values in the template.111+112+ `finalize`113+ A callable that finalizes the variable. Per default no finalizing114+ is applied.115+116+ `autoescape`117+ If set to true the XML/HTML autoescaping feature is enabled.118+119+ `loader`120+ The template loader for this environment.121 """122 123 #: if this environment is sandboxed. Modifying this variable won't make124 #: the environment sandboxed though. For a real sandboxed environment15 unmodified lines140 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 to3 unmodified lines153 # - 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:157 110- ========================= ============================================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- """138-158 # 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 lines175 # runtime information176 self.undefined = undefined177 self.optimized = optimized178 self.finalize = finalize179+ self.autoescape = autoescape180 181 # defaults182 self.filters = DEFAULT_FILTERS.copy()183 self.tests = DEFAULT_TESTS.copy()22 unmodified lines206 except (TypeError, LookupError):207 return self.undefined(obj=obj, name=argument)208 209 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()216 217 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)201-202- 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)222 223 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.234+235+ 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 lines251 return compile(source, filename, 'exec')252 253 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.259+260+ Subclasses may override this method and implement template path261+ joining here.262+ """263 return template264 265 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.270+271+ 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.274+275+ 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))283 284 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 lines299 class Template(object):300 """The central template object. This class represents a compiled template301 and is used to evaluate it.302 258- 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.307 308 Every template object has a few methods and members that are guaranteed29 unmodified lines338 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)350 351 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::355+356+ template.render(knights='that say nih')357+ template.render({'knights': 'that say nih'})358+359+ 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_next367 368 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_next378 379 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.384+385+ It accepts the same arguments as :meth:`render`.386+ """387 # assemble the context388 context = dict(*args, **kwargs)389 390 # if the environment is using the optimizer locals may never34 unmodified lines425 return TemplateContext(self.environment, parent, self.name,426 self.blocks)427 428 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.434+435+ 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.438+439+ This example shows how it can be used:440+441+ >>> 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 lines507 return '<%s %s>' % (self.__class__.__name__, name)508 509 510 class 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.515+516+ 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 """520 521 def __init__(self, gen):522 self._gen = gen5 unmodified lines528 self._next = self._gen.next529 self.buffered = False530 531 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')535 536 def generator():30 unmodified linesmodified:jinja2/exceptions.py+3 added-5 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~5 6 Jinja exceptions.7 8- :copyright: 2007 by Armin Ronacher.8+ :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 1 unmodified line14 """Baseclass for all template errors."""15 16 17 class UndefinedError(TemplateError):18- """Raised if a template tries to operate on `Undefined`."""18+ """Raised if a template tries to operate on :class:`Undefined`."""19 20 21 class TemplateNotFound(IOError, LookupError, TemplateError):22 """Raised if a template does not exist."""20 unmodified lines43 """44 45 46 class 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 lines15 from jinja2.environment import get_spontaneous_environment16 from jinja2.runtime import Undefined, concat17 from jinja2.parser import statement_end_tokens18 from jinja2.exceptions import TemplateAssertionError19-from jinja2.utils import import_string19+from jinja2.utils import import_string, Markup20 21 22 # the only real useful gettext functions for a Jinja template. Note23 # that ugettext must be assigned to gettext as Jinja doesn't support261 unmodified lines285 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 )291 292 node = environment.parse(fileobj.read().decode(encoding))293 for lineno, func, message in extract_from_ast(node, keywords):1 unmodified linemodified:jinja2/filters.py+19 added-15 removed
49 unmodified lines50 value = value.__html__()51 return escape(unicode(value))52 53 54+@environmentfilter54-def do_replace(s, old, new, count=None):55+def 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 first8 unmodified lines68 -> 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 lines88 """Convert a value to lowercase."""89 return soft_unicode(s).lower()90 91 89-def do_xmlattr(d, autospace=False):92+@environmentfilter93+def 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 lines110 ...111 </ul>112 113 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 rv126 127 128 def do_capitalize(s):129 """Capitalize a value. The first character will be uppercase, all others65 unmodified lines195 return default_value196 return value197 198 199+@environmentfilter200-def do_join(value, d=u''):200+def 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 lines209 210 {{ [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))216+217 # 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 linesmodified:jinja2/loaders.py+114 added-21 removed
29 unmodified lines30 31 32 class 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.37 36- 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::40+41+ from jinja2 import BaseLoader, TemplateNotFound42+ from os.path import join, exists, getmtime43+44+ class MyLoader(BaseLoader):45+46+ def __init__(self, path, cache_size=50, auto_reload=True):47+ BaseLoader.__init__(self, cache_size, auto_reload)48+ self.path = path49+50+ 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 """59 60 def __init__(self, cache_size=50, auto_reload=True):61 if cache_size == 0:24 unmodified lines86 """87 raise TemplateNotFound(template)88 89 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 lines110 return template111 112 113 class 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.116 117+ 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:120+121+ >>> loader = FileSystemLoader('/path/to/templates')122+ >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])123+124+ Per default the template encoding is ``'utf-8'`` which can be changed125+ by setting the `encoding` parameter to something else.126+ """127+128 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 = encoding135 136 def get_source(self, environment, template):137 pieces = split_template_path(template)11 unmodified lines149 raise TemplateNotFound(template)150 151 152 class 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:156 157+ >>> loader = PackageLoader('mypackage', 'views')158+159+ If the package path is not given, ``'templates'`` is assumed.160+161+ 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+ """166+120- 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_path177 178 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, None183 184+ 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) != mtime190 191+ source = self.provider.get_resource_string(self.manager, p)192+ return source.decode(self.encoding), filename, uptodate193+194+195 class 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:198 199+ >>> loader = DictLoader({'index.html': 'source here'})200+201+ Because auto reloading is rarely useful this is disabled per default.202+ """203+139- 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 = mapping207 208 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)213 214 215 class 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.220+221+ >>> def load_template(name):222+ ... if name == 'index.html'223+ ... return '...'224+ ...225+ >>> loader = FunctionLoader(load_template)226+227+ 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 """232 233 def __init__(self, load_func, cache_size=50, auto_reload=True):234 BaseLoader.__init__(self, cache_size, auto_reload)11 unmodified lines246 class 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:251+252+ >>> loader = PrefixLoader({253+ ... 'app1': PackageLoader('mypackage.app1'),254+ ... 'app2': PackageLoader('mypackage.app2')255+ ... })256+257+ 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 """260 261 def __init__(self, mapping, delimiter='/', cache_size=50,262 auto_reload=True):14 unmodified lines277 """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.281+282+ >>> loader = ChoiceLoader([283+ ... FileSystemLoader('/path/to/user/templates'),284+ ... PackageLoader('myapplication')285+ ])286+287+ This is useful if you want to allow users to override builtin templates288+ from a different location.289 """290 291 def __init__(self, loaders, cache_size=50, auto_reload=True):292 BaseLoader.__init__(self, cache_size, auto_reload)9 unmodified linesmodified:jinja2/runtime.py+64 added-9 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11 from types import FunctionType12-from jinja2.utils import Markup, partial13-from jinja2.exceptions import UndefinedError12+from itertools import chain, imap13+from jinja2.utils import Markup, partial, soft_unicode, escape14+from jinja2.exceptions import UndefinedError, TemplateRuntimeError15 16 17 # 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']21 22 23 # special singleton representing missing values for the runtime24 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()2 unmodified lines27 # concatenate a list of strings and convert them to unicode.28 concat = u''.join29 30 31+def 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)40+41+42+def unicode_join(*args):43+ """Simple args to unicode conversion and concatenation."""44+ return concat(imap(unicode, args))45+46+47 class 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 update34 unmodified lines85 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 render93 94 def get(self, key, default=None):46 unmodified lines141 self.__context = context142 143 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 render150 151 def __repr__(self):137 unmodified lines289 raise UndefinedError(hint)290 291 292 class 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`:295+296+ >>> 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')307 308 def __init__(self, hint=None, obj=None, name=None):27 unmodified lines336 return False337 338 339 class DebugUndefined(Undefined):310- """An undefined that returns the debug info when printed."""340+ """An undefined that returns the debug info when printed.341+342+ >>> 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__ = ()353 354 def __unicode__(self):355 if self._undefined_hint is None:9 unmodified lines365 class 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.369+370+ >>> 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_error5 unmodified lines