blob: 5b77d45c9475654347ed40a88d19f3614880f451 [file] [log] [blame]
Armin Ronacher07bc6842008-03-31 14:18:49 +02001# -*- coding: utf-8 -*-
2"""
Armin Ronacher82b3f3d2008-03-31 20:01:08 +02003 jinja2.environment
4 ~~~~~~~~~~~~~~~~~~
Armin Ronacher07bc6842008-03-31 14:18:49 +02005
6 Provides a class that holds runtime and parsing time options.
7
Armin Ronacher19cf9c22008-05-01 12:49:53 +02008 :copyright: 2008 by Armin Ronacher.
Armin Ronacher07bc6842008-03-31 14:18:49 +02009 :license: BSD, see LICENSE for more details.
10"""
Armin Ronacherba3757b2008-04-16 19:43:16 +020011import sys
Armin Ronacher7259c762008-04-30 13:03:59 +020012from jinja2.defaults import *
Armin Ronacher9a0078d2008-08-13 18:24:17 +020013from jinja2.lexer import get_lexer, TokenStream
Armin Ronacher05530932008-04-20 13:27:49 +020014from jinja2.parser import Parser
Armin Ronacherbcb7c532008-04-11 16:30:34 +020015from jinja2.optimizer import optimize
16from jinja2.compiler import generate
Armin Ronacher7ceced52008-05-03 10:15:31 +020017from jinja2.runtime import Undefined, Context
Armin Ronacheraaf010d2008-05-01 13:14:30 +020018from jinja2.exceptions import TemplateSyntaxError
Armin Ronacher7ceced52008-05-03 10:15:31 +020019from jinja2.utils import import_string, LRUCache, Markup, missing, concat
Armin Ronacher07bc6842008-03-31 14:18:49 +020020
21
Armin Ronacher203bfcb2008-04-24 21:54:44 +020022# for direct template usage we have up to ten living environments
23_spontaneous_environments = LRUCache(10)
24
25
Armin Ronacherb5124e62008-04-25 00:36:14 +020026def get_spontaneous_environment(*args):
Armin Ronacher203bfcb2008-04-24 21:54:44 +020027 """Return a new spontaneus environment. A spontaneus environment is an
28 unnamed and unaccessable (in theory) environment that is used for
29 template generated from a string and not from the file system.
30 """
31 try:
32 env = _spontaneous_environments.get(args)
33 except TypeError:
34 return Environment(*args)
35 if env is not None:
36 return env
37 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020038 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020039 return env
40
41
Armin Ronacher7259c762008-04-30 13:03:59 +020042def create_cache(size):
43 """Return the cache class for the given size."""
44 if size == 0:
45 return None
46 if size < 0:
47 return {}
48 return LRUCache(size)
49
50
51def load_extensions(environment, extensions):
52 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020053 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020054 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020055 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020056 for extension in extensions:
57 if isinstance(extension, basestring):
58 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020059 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020060 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020061
Armin Ronacher203bfcb2008-04-24 21:54:44 +020062
Armin Ronacher7259c762008-04-30 13:03:59 +020063def _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'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020071 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
72 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020073 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020074
75
Armin Ronacher07bc6842008-03-31 14:18:49 +020076class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020077 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020078 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020079 globals and others. Instances of this class may be modified if
80 they are not shared and if no template was loaded so far.
81 Modifications on environments after the first template was loaded
82 will lead to surprising effects and undefined behavior.
83
84 Here the possible initialization parameters:
85
Armin Ronacher7b5680c2008-05-06 16:54:22 +020086 `block_start_string`
87 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020088
Armin Ronacher7b5680c2008-05-06 16:54:22 +020089 `block_end_string`
90 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020091
Armin Ronacher7b5680c2008-05-06 16:54:22 +020092 `variable_start_string`
93 The string marking the begin of a print statement.
94 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +020095
Armin Ronacher63fd7982008-06-20 18:47:56 +020096 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +020097 The string marking the end of a print statement. Defaults to
98 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020099
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200100 `comment_start_string`
101 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200102
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200103 `comment_end_string`
104 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200105
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200106 `line_statement_prefix`
107 If given and a string, this will be used as prefix for line based
108 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200109
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200110 `trim_blocks`
111 If this is set to ``True`` the first newline after a block is
112 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200113
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200114 `newline_sequence`
115 The sequence that starts a newline. Must be one of ``'\r'``,
116 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
117 useful default for Linux and OS X systems as well as web
118 applications.
119
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200120 `extensions`
121 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200122 as strings or extension classes. For more information have a
123 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200124
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200125 `optimized`
126 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200127
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200128 `undefined`
129 :class:`Undefined` or a subclass of it that is used to represent
130 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200131
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200132 `finalize`
133 A callable that finalizes the variable. Per default no finalizing
134 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200135
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200136 `autoescape`
137 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200138 For more details about auto escaping see
139 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200140
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200141 `loader`
142 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200143
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200144 `cache_size`
145 The size of the cache. Per default this is ``50`` which means
146 that if more than 50 templates are loaded the loader will clean
147 out the least recently used template. If the cache size is set to
148 ``0`` templates are recompiled all the time, if the cache size is
149 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200150
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200151 `auto_reload`
152 Some loaders load templates from locations where the template
153 sources may change (ie: file system or database). If
154 `auto_reload` is set to `True` (default) every time a template is
155 requested the loader checks if the source changed and if yes, it
156 will reload the template. For higher performance it's possible to
157 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200158
159 `bytecode_cache`
160 If set to a bytecode cache object, this object will provide a
161 cache for the internal Jinja bytecode so that templates don't
162 have to be parsed if they were not changed.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200163 """
164
Armin Ronacherc63243e2008-04-14 22:53:58 +0200165 #: if this environment is sandboxed. Modifying this variable won't make
166 #: the environment sandboxed though. For a real sandboxed environment
167 #: have a look at jinja2.sandbox
168 sandboxed = False
169
Armin Ronacher7259c762008-04-30 13:03:59 +0200170 #: True if the environment is just an overlay
171 overlay = False
172
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200173 #: the environment this environment is linked to if it is an overlay
174 linked_to = None
175
Armin Ronacherc9705c22008-04-27 21:28:03 +0200176 #: shared environments have this set to `True`. A shared environment
177 #: must not be modified
178 shared = False
179
Armin Ronacher07bc6842008-03-31 14:18:49 +0200180 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200181 block_start_string=BLOCK_START_STRING,
182 block_end_string=BLOCK_END_STRING,
183 variable_start_string=VARIABLE_START_STRING,
184 variable_end_string=VARIABLE_END_STRING,
185 comment_start_string=COMMENT_START_STRING,
186 comment_end_string=COMMENT_END_STRING,
187 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200188 trim_blocks=TRIM_BLOCKS,
189 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200190 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200191 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200192 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200193 finalize=None,
194 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200195 loader=None,
196 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200197 auto_reload=True,
198 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200199 # !!Important notice!!
200 # The constructor accepts quite a few arguments that should be
201 # passed by keyword rather than position. However it's important to
202 # not change the order of arguments because it's used at least
203 # internally in those cases:
204 # - spontaneus environments (i18n extension and Template)
205 # - unittests
206 # If parameter changes are required only add parameters at the end
207 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200208 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200209
210 # lexer / parser information
211 self.block_start_string = block_start_string
212 self.block_end_string = block_end_string
213 self.variable_start_string = variable_start_string
214 self.variable_end_string = variable_end_string
215 self.comment_start_string = comment_start_string
216 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200217 self.line_statement_prefix = line_statement_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200218 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200219 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200220
Armin Ronacherf59bac22008-04-20 13:11:43 +0200221 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200222 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200223 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200224 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200225 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200226
227 # defaults
228 self.filters = DEFAULT_FILTERS.copy()
229 self.tests = DEFAULT_TESTS.copy()
230 self.globals = DEFAULT_NAMESPACE.copy()
231
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200232 # set the loader provided
233 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200234 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200235 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200236 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200237 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200238
Armin Ronacherb5124e62008-04-25 00:36:14 +0200239 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200240 self.extensions = load_extensions(self, extensions)
241
242 _environment_sanity_check(self)
243
Armin Ronacher762079c2008-05-08 23:57:56 +0200244 def extend(self, **attributes):
245 """Add the items to the instance of the environment if they do not exist
246 yet. This is used by :ref:`extensions <writing-extensions>` to register
247 callbacks and configuration values without breaking inheritance.
248 """
249 for key, value in attributes.iteritems():
250 if not hasattr(self, key):
251 setattr(self, key, value)
252
Armin Ronacher7259c762008-04-30 13:03:59 +0200253 def overlay(self, block_start_string=missing, block_end_string=missing,
254 variable_start_string=missing, variable_end_string=missing,
255 comment_start_string=missing, comment_end_string=missing,
256 line_statement_prefix=missing, trim_blocks=missing,
257 extensions=missing, optimized=missing, undefined=missing,
258 finalize=missing, autoescape=missing, loader=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200259 cache_size=missing, auto_reload=missing,
260 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200261 """Create a new overlay environment that shares all the data with the
262 current environment except of cache and the overriden attributes.
263 Extensions cannot be removed for a overlayed environment. A overlayed
264 environment automatically gets all the extensions of the environment it
265 is linked to plus optional extra extensions.
266
267 Creating overlays should happen after the initial environment was set
268 up completely. Not all attributes are truly linked, some are just
269 copied over so modifications on the original environment may not shine
270 through.
271 """
272 args = dict(locals())
273 del args['self'], args['cache_size'], args['extensions']
274
275 rv = object.__new__(self.__class__)
276 rv.__dict__.update(self.__dict__)
277 rv.overlay = True
278 rv.linked_to = self
279
280 for key, value in args.iteritems():
281 if value is not missing:
282 setattr(rv, key, value)
283
284 if cache_size is not missing:
285 rv.cache = create_cache(cache_size)
286
Armin Ronacher023b5e92008-05-08 11:03:10 +0200287 rv.extensions = {}
288 for key, value in self.extensions.iteritems():
289 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200290 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200291 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200292
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200293 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200294
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200295 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200296
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200297 def getitem(self, obj, argument):
298 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200299 try:
300 return obj[argument]
301 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200302 if isinstance(argument, basestring):
303 try:
304 attr = str(argument)
305 except:
306 pass
307 else:
308 try:
309 return getattr(obj, attr)
310 except AttributeError:
311 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200312 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200313
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200314 def getattr(self, obj, attribute):
315 """Get an item or attribute of an object but prefer the attribute.
316 Unlike :meth:`getitem` the attribute *must* be a bytestring.
317 """
318 try:
319 return getattr(obj, attribute)
320 except AttributeError:
321 pass
322 try:
323 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200324 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200325 return self.undefined(obj=obj, name=attribute)
326
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200327 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200328 """Parse the sourcecode and return the abstract syntax tree. This
329 tree of nodes is used by the compiler to convert the template into
330 executable source- or bytecode. This is useful for debugging or to
331 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200332
333 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
334 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200335 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200336 if isinstance(filename, unicode):
337 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200338 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200339 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200340 except TemplateSyntaxError, e:
Armin Ronacher27069d72008-05-11 19:48:12 +0200341 from jinja2.debug import translate_syntax_error
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200342 exc_type, exc_value, tb = translate_syntax_error(e)
343 raise exc_type, exc_value, tb
Armin Ronacher07bc6842008-03-31 14:18:49 +0200344
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200345 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200346 """Lex the given sourcecode and return a generator that yields
347 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200348 This can be useful for :ref:`extension development <writing-extensions>`
349 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200350
351 This does not perform preprocessing. If you want the preprocessing
352 of the extensions to be applied you have to filter source through
353 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200354 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200355 return self.lexer.tokeniter(unicode(source), name, filename)
356
357 def preprocess(self, source, name=None, filename=None):
358 """Preprocesses the source with all extensions. This is automatically
359 called for all parsing and compiling methods but *not* for :meth:`lex`
360 because there you usually only want the actual source tokenized.
361 """
362 return reduce(lambda s, e: e.preprocess(s, name, filename),
363 self.extensions.itervalues(), unicode(source))
364
365 def _tokenize(self, source, name, filename=None):
366 """Called by the parser to do the preprocessing and filtering
367 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
368 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200369 source = self.preprocess(source, name, filename)
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200370 stream = self.lexer.tokenize(source, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200371 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200372 stream = ext.filter_stream(stream)
373 if not isinstance(stream, TokenStream):
374 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200375 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200376
Armin Ronacher981cbf62008-05-13 09:12:27 +0200377 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200378 """Compile a node or template source code. The `name` parameter is
379 the load name of the template after it was joined using
380 :meth:`join_path` if necessary, not the filename on the file system.
381 the `filename` parameter is the estimated filename of the template on
382 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200383 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200384
385 The return value of this method is a python code object. If the `raw`
386 parameter is `True` the return value will be a string with python
387 code equivalent to the bytecode returned otherwise. This method is
388 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200389 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200390 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200391 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200392 if self.optimized:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200393 node = optimize(source, self)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200394 source = generate(node, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200395 if raw:
396 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200397 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200398 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200399 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200400 filename = filename.encode('utf-8')
401 return compile(source, filename, 'exec')
402
403 def join_path(self, template, parent):
404 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200405 relative to the loader root so this method returns the `template`
406 parameter unchanged, but if the paths should be relative to the
407 parent template, this function can be used to calculate the real
408 template name.
409
410 Subclasses may override this method and implement template path
411 joining here.
412 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200413 return template
414
Armin Ronacherfed44b52008-04-13 19:42:53 +0200415 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200416 """Load a template from the loader. If a loader is configured this
417 method ask the loader for the template and returns a :class:`Template`.
418 If the `parent` parameter is not `None`, :meth:`join_path` is called
419 to get the real template name before loading.
420
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200421 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200422 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200423
424 If the template does not exist a :exc:`TemplateNotFound` exception is
425 raised.
426 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200427 if self.loader is None:
428 raise TypeError('no loader for this environment specified')
429 if parent is not None:
430 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200431
432 if self.cache is not None:
433 template = self.cache.get(name)
434 if template is not None and (not self.auto_reload or \
435 template.is_up_to_date):
436 return template
437
438 template = self.loader.load(self, name, self.make_globals(globals))
439 if self.cache is not None:
440 self.cache[name] = template
441 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200442
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200443 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200444 """Load a template from a string. This parses the source given and
445 returns a :class:`Template` object.
446 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200447 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200448 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200449 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200450
451 def make_globals(self, d):
452 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200453 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200454 return self.globals
455 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200456
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200457
458class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200459 """The central template object. This class represents a compiled template
460 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200461
Armin Ronacherd1342312008-04-28 12:20:12 +0200462 Normally the template object is generated from an :class:`Environment` but
463 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200464 instance directly using the constructor. It takes the same arguments as
465 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200466
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200467 Every template object has a few methods and members that are guaranteed
468 to exist. However it's important that a template object should be
469 considered immutable. Modifications on the object are not supported.
470
471 Template objects created from the constructor rather than an environment
472 do have an `environment` attribute that points to a temporary environment
473 that is probably shared with other templates created with the constructor
474 and compatible settings.
475
476 >>> template = Template('Hello {{ name }}!')
477 >>> template.render(name='John Doe')
478 u'Hello John Doe!'
479
480 >>> stream = template.stream(name='John Doe')
481 >>> stream.next()
482 u'Hello John Doe!'
483 >>> stream.next()
484 Traceback (most recent call last):
485 ...
486 StopIteration
487 """
488
489 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200490 block_start_string=BLOCK_START_STRING,
491 block_end_string=BLOCK_END_STRING,
492 variable_start_string=VARIABLE_START_STRING,
493 variable_end_string=VARIABLE_END_STRING,
494 comment_start_string=COMMENT_START_STRING,
495 comment_end_string=COMMENT_END_STRING,
496 line_statement_prefix=LINE_STATEMENT_PREFIX,
497 trim_blocks=TRIM_BLOCKS,
498 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200499 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200500 optimized=True,
501 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200502 finalize=None,
503 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200504 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200505 block_start_string, block_end_string, variable_start_string,
506 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200507 line_statement_prefix, trim_blocks, newline_sequence,
508 frozenset(extensions), optimized, undefined, finalize,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200509 autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200510 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200511
Armin Ronacher7259c762008-04-30 13:03:59 +0200512 @classmethod
513 def from_code(cls, environment, code, globals, uptodate=None):
514 """Creates a template object from compiled code and the globals. This
515 is used by the loaders and environment to create a template object.
516 """
517 t = object.__new__(cls)
518 namespace = {
519 'environment': environment,
520 '__jinja_template__': t
521 }
522 exec code in namespace
523 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200524 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200525 t.name = namespace['name']
526 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200527 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200528
529 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200530 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200531 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200532
533 # debug and loader helpers
534 t._debug_info = namespace['debug_info']
535 t._uptodate = uptodate
536
537 return t
538
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200539 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200540 """This method accepts the same arguments as the `dict` constructor:
541 A dict, a dict subclass or some keyword arguments. If no arguments
542 are given the context will be empty. These two calls do the same::
543
544 template.render(knights='that say nih')
545 template.render({'knights': 'that say nih'})
546
547 This will return the rendered template as unicode string.
548 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200549 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200550 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200551 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200552 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200553 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200554 exc_type, exc_value, tb = translate_exception(sys.exc_info())
555 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200556
557 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200558 """Works exactly like :meth:`generate` but returns a
559 :class:`TemplateStream`.
560 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200561 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200562
563 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200564 """For very large templates it can be useful to not render the whole
565 template at once but evaluate each statement after another and yield
566 piece for piece. This method basically does exactly that and returns
567 a generator that yields one item after another as unicode strings.
568
569 It accepts the same arguments as :meth:`render`.
570 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200571 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200572 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200573 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200574 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200575 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200576 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200577 exc_type, exc_value, tb = translate_exception(sys.exc_info())
578 raise exc_type, exc_value, tb
579
Armin Ronacherc9705c22008-04-27 21:28:03 +0200580 def new_context(self, vars=None, shared=False):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200581 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200582 provided will be passed to the template. Per default the globals
583 are added to the context, if shared is set to `True` the data
584 provided is used as parent namespace. This is used to share the
585 same globals in multiple contexts without consuming more memory.
586 (This works because the context does not modify the parent dict)
587 """
588 if vars is None:
589 vars = {}
590 if shared:
591 parent = vars
592 else:
593 parent = dict(self.globals, **vars)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200594 return Context(self.environment, parent, self.name, self.blocks)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200595
Armin Ronacherea847c52008-05-02 20:04:32 +0200596 def make_module(self, vars=None, shared=False):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200597 """This method works like the :attr:`module` attribute when called
598 without arguments but it will evaluate the template every call
599 rather then caching the template. It's also possible to provide
600 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200601 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200602 """
603 return TemplateModule(self, self.new_context(vars, shared))
604
Armin Ronacherd84ec462008-04-29 13:43:16 +0200605 @property
606 def module(self):
607 """The template as module. This is used for imports in the
608 template runtime but is also useful if one wants to access
609 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200610
Armin Ronacherd84ec462008-04-29 13:43:16 +0200611 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
612 >>> unicode(t.module)
613 u'23'
614 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200615 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200616 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200617 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200618 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200619 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200620 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200621
Armin Ronacherba3757b2008-04-16 19:43:16 +0200622 def get_corresponding_lineno(self, lineno):
623 """Return the source line number of a line number in the
624 generated bytecode as they are not in sync.
625 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200626 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200627 if code_line <= lineno:
628 return template_line
629 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200630
Armin Ronacher9a822052008-04-17 18:44:07 +0200631 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200632 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200633 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200634 if self._uptodate is None:
635 return True
636 return self._uptodate()
637
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200638 @property
639 def debug_info(self):
640 """The debug info mapping."""
641 return [tuple(map(int, x.split('='))) for x in
642 self._debug_info.split('&')]
643
Armin Ronacherc63243e2008-04-14 22:53:58 +0200644 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200645 if self.name is None:
646 name = 'memory:%x' % id(self)
647 else:
648 name = repr(self.name)
649 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200650
651
Armin Ronacherd84ec462008-04-29 13:43:16 +0200652class TemplateModule(object):
653 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200654 template are available as attributes on this object. Additionally
655 converting it into an unicode- or bytestrings renders the contents.
656 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200657
658 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200659 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200660 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200661 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200662
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200663 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200664 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200665
666 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200667 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200668
669 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200670 if self.__name__ is None:
671 name = 'memory:%x' % id(self)
672 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200673 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200674 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200675
676
Armin Ronacherc63243e2008-04-14 22:53:58 +0200677class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200678 """A template stream works pretty much like an ordinary python generator
679 but it can buffer multiple items to reduce the number of total iterations.
680 Per default the output is unbuffered which means that for every unbuffered
681 instruction in the template one unicode string is yielded.
682
683 If buffering is enabled with a buffer size of 5, five items are combined
684 into a new unicode string. This is mainly useful if you are streaming
685 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200686 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200687
688 def __init__(self, gen):
689 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200690 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200691
Armin Ronacher74b51062008-06-17 11:28:59 +0200692 def dump(self, fp, encoding=None, errors='strict'):
693 """Dump the complete stream into a file or file-like object.
694 Per default unicode strings are written, if you want to encode
695 before writing specifiy an `encoding`.
696
697 Example usage::
698
699 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
700 """
701 close = False
702 if isinstance(fp, basestring):
703 fp = file(fp, 'w')
704 close = True
705 try:
706 if encoding is not None:
707 iterable = (x.encode(encoding, errors) for x in self)
708 else:
709 iterable = self
710 if hasattr(fp, 'writelines'):
711 fp.writelines(iterable)
712 else:
713 for item in iterable:
714 fp.write(item)
715 finally:
716 if close:
717 fp.close()
718
Armin Ronacherc63243e2008-04-14 22:53:58 +0200719 def disable_buffering(self):
720 """Disable the output buffering."""
721 self._next = self._gen.next
722 self.buffered = False
723
724 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200725 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200726 if size <= 1:
727 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200728
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200729 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200730 buf = []
731 c_size = 0
732 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200733
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200734 while 1:
735 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200736 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200737 c = next()
738 push(c)
739 if c:
740 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200741 except StopIteration:
742 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200743 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200744 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200745 del buf[:]
746 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200747
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200748 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200749 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200750
751 def __iter__(self):
752 return self
753
754 def next(self):
755 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200756
757
758# hook in default template class. if anyone reads this comment: ignore that
759# it's possible to use custom templates ;-)
760Environment.template_class = Template