Skip to content
Myr

[svn] many jinja changes:

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

- improved generated bytecode - improved streaming system - buffer variable substitution syntax --HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 6c939e7 · Browse files · 20 files+1154 added−517 removed
This commit

State

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

Diff stats

20 files+1154 added−517 removed

  • tests:+38 added−1 removed
  • other:+1116 added−516 removed

20 files+1154 added−517 removed

added:docs/src/api.txt+315 added
1=======================2Context and Environment3=======================45The two central objects in Jinja are the `Environment` and `Context`. Both6are designed to be subclassed by applications if they need to extend Jinja.78Environment9===========1011The initialization parameters are already covered in the `Quickstart`_ thus12not repeated here.1314But beside those configurable instance variables there are some functions used15in the template evaluation code you may want to override:1617**def** `parse` *(source, filename)*:1819 Parse the sourcecode and return the abstract syntax tree. This tree of20 nodes is used by the `translators`_ to convert the template into21 executable source- or bytecode.2223**def** `lex` *(source, filename)*:2425 Tokenize the given sourcecode and return a generator of tuples in the26 form ``(lineno, token, value)``. The filename is just used in the27 exceptions raised.28 29 **New in Jinja 1.1**3031**def** `from_string` *(source)*:3233 Load and parse a template source and translate it into eval-able Python34 code. This code is wrapped within a `Template` class that allows you to35 render it.3637**def** `get_template` *(name)*:3839 Load a template from a loader. If the template does not exist, you will40 get a `jinja.exceptions.TemplateNotFound` exception.4142**def** `to_unicode` *(self, value)*:4344 Called to convert variables to unicode. Per default this checks if the45 value is already unicode. If not it's converted to unicode using the46 charset defined on the environment.4748 Also `None` is converted into an empty string per default.4950**def** `get_translator` *(self, context)*:5152 Return the translator used for i18n. A translator is an object that53 provides the two functions ``gettext(string)`` and54 ``ngettext(singular, plural, n)``. Both of those functions have to55 behave like the `ugettext` and `nugettext` functions described in the56 python `gettext documentation`_.5758 If you don't provide a translator a default one is used to switch59 between singular and plural forms.6061 Have a look at the `i18n`_ section for more information.6263**def** `get_translations` *(self, name)*:6465 Get the translations for the template `name`. Only works if a loader66 is present. See the `i18n`_ section for more details.6768**def** `get_translations_for_string` *(self, string)*:6970 Get the translations for the string `string`. This works also if no71 loader is present and can be used to lookup translation strings from72 templates that are loaded from dynamic resources like databases.7374**def** `apply_filters` *(self, value, context, filters)*:7576 Now this function is a bit tricky and you usually don't have to override77 it. It's used to apply filters on a value. The Jinja expression78 ``{{ foo|escape|replace('a', 'b') }}`` calls the function with the79 value of `foo` as first parameter, the current context as second and80 a list of filters as third. The list looks like this:8182 .. sourcecode:: python8384 [('escape', ()), ('replace', (u'a', u'b'))]8586 As you can see the filter `escape` is called without arguments whereas87 `replace` is called with the two literal strings ``a`` and ``b``, both88 unicode. The filters for the names are stored on ``self.filters`` in a89 dict. Missing filters should raise a `FilterNotFound` exception.9091 **Warning** this is a Jinja internal method. The actual implementation92 and function signature might change.9394**def** `perform_test` *(self, context, testname, args, value, invert)*:9596 Like `apply_filters` you usually don't override this one. It's the97 callback function for tests (``foo is bar`` / ``foo is not bar``).9899 The first parameter is the current contex, the second the name of100 the test to perform. the third a tuple of arguments, the fourth is101 the value to test. The last one is `True` if the test was performed102 with the `is not` operator, `False` if with the `is` operator.103104 Missing tests should raise a `TestNotFound` exception.105106 **Warning** this is a Jinja internal method. The actual implementation107 and function signature might change.108109**def** `get_attribute` *(self, obj, attribute)*:110111 Get `attribute` from the object provided. The default implementation112 performs security tests.113114 **Warning** this is a Jinja internal method. The actual implementation115 and function signature might change.116117**def** `get_attributes` *(self, obj, attributes)*:118119 Get some attributes from the object. If `attributes` is an empty120 sequence the object itself is returned unchanged.121122**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:123 124 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and125 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`126 is not `None` you have to add it to the arguments, if `dyn_kwargs` is127 not `None` you have to update the `kwargs` with it.128129 The default implementation performs some security checks.130131 **Warning** this is a Jinja internal method. The actual implementation132 and function signature might change.133134**def** `call_function_simple` *(self, f, context)*:135136 Like `call_function` but without arguments.137138 **Warning** this is a Jinja internal method. The actual implementation139 and function signature might change.140141**def** `finish_var` *(self, value, ctx)*:142143 Postprocess a variable before it's sent to the template.144145 **Warning** this is a Jinja internal method. The actual implementation146 and function signature might change.147 148.. admonition:: Note149150 The Enviornment class is defined in `jinja.environment.Environment`151 but imported into the `jinja` package because it's often used.152153Context154=======155156Jinja wraps the variables passed to the template in a special class called a157context. This context supports variables on multiple layers and lazy (deferred)158objects. Often your application has a request object, database connection159object or something similar you want to access in filters, functions etc.160161The default context object is defined in `jinja.datastructure`. If you want162to provide your own context object always subclass the default one. This163ensures that the class continues working after Jinja upgrades.164165Beacause of that you can easily subclass a context to add additional variables166or to change the way it behaves.167168**def** `pop` *(self)*:169170 Pop the outermost layer and return it.171172**def** `push` *(self, data=None)*:173174 Push a dict to the stack or an empty layer.175176 Has to return the pushed object.177178**def** `to_dict` *(self)*:179180 Flatten the context and convert it into a dict.181182**def** `__getitem__` *(self, name)*:183184 Resolve an item. Per default this also resolves `Deferred` objects.185186**def** `__setitem__` *(self, name, value)*:187188 Set an item in the outermost layer.189190**def** `__delitem__` *(self, name)*:191192 Delete an item in the outermost layer. Do not raise exceptions if193 the value does not exist.194195**def** `__contains__` *(self, name)*:196197 Return `True` if `name` exists in the context.198199**attribute** `cache`:200201 The cache is a dict which can be used by filters, test functions202 and global objects to cache data. It's also used by the environment203 to cache often used tests and filters.204205**attribute** `translate_func`:206207 This property is created on first access and returns a translation208 function used by the rendering process to translate strings with the209 translator defined on the environment.210211.. admonition:: Note212213 The context uses a stack of dicts internally to represent the214 layers of variables. It contains at least 3 levels available on215 the context with some attributes. Those are:216217 `globals`:218 219 The reference to the global namespace of the environment.220 It's the lowest namespace on the stack and thus immutable221222 `initial`:223224 The initial namespace. Contains the values passed to the225 context in the render function. It also contains the resolved226 deferred values for bot the `initial` and the `globals`227 namespace.228229 `current`:230231 The reference to the current active namespace. When the232 context is initialized this automatically points to an233 empty namespace.234235 The number of layers on the stack are theoretically unlimited.236 Some elements in the template language like loops, blocks,237 macros and others push and pop the layer on entering and leaving238 the section.239240 This is done in order to keep the namespace clean.241242 Note that since Jinja 1.1 the context object is a subclass of the243 `BaseContext`, a much simpler class that just implements a stack244 like namespace for python. If the `_speedups` extension was245 compiled for jinja the base class will be246 `jinja._speedups.BaseContext` otherwise `jinja._native.BaseContext`.247248 Since you cannot reproduce completely the same semantics in python249 and the C API there are some things you should keep in mind:250251 - The `stack` attribute of the context maps to the real layers252 on the stack, thus you can modify the items but the list as253 such is meant to be read only.254255 - `globals`, `current` and `initial` are read only attributes that256 map to layers on the stack which you can of course modify.257258259Exceptions260==========261262During parsing and evaluation Jinja raises a couple of Jinja specific263exceptions. All of those exceptions are defined in the `jinja.exceptions`264module and are subclasses of the `TemplateError` class defined there.265266Here a list of exceptions that could occur:267268`SecurityException`:269270 An exception that is raised if the template tried to access something271 it should not access. In the default configuration this exception272 will get caught in the Jinja rendering process and silenced.273274 If however the environment is configured to not silently fail it275 could happen that this exception reaches the application.276277`FilterNotFound`:278279 Raised if the template tried to apply a filter that does not exist.280 Since this exception is a subclass of `KeyError` too you can catch281 it this way too.282283`FilterArgumentError`:284285 Raised if the filter received an argument that it couldn't handle.286 It's a subclass of `TypeError` too so you can catch it this way too.287288`TestNotFound`:289290 Raised if the template tried to perform a test that does not exist.291 Since this exception is a subclass of `KeyError` too you can catch292 it this way too.293294`TestArgumentError`:295296 Raised if a test function received an argument that it couldn't handle.297 It's a subclass of `TypeError` too so you can catch it this way too.298299`TemplateNotFound`:300301 Raised if a template does not exist. Subclass of `IOError` too.302303`TemplateSyntaxError`:304305 Subclass of `SyntaxError` and used to indicate an syntax error.306307`TemplateRuntimeError`:308309 Generic runtime error exception which can occour at various places.310311312.. _i18n: i18n.txt313.. _translators: translators.txt314.. _Quickstart: devintro.txt315.. _gettext documentation: http://docs.python.org/lib/module-gettext.html
modified:docs/src/designerdoc.txt+146 added-56 removed
233 unmodified lines
234 is checked.235236 *new in Jinja 1.1*237238`flush`239 240 Jinja 1.1 includes a new stream interface which can be used to speed241 up the generation of big templates by streaming them to the client.242 Per default Jinja flushes after 40 actions automatically. If you243 want to force a flush at a special point you can use `flush()` to244 do so. (eg, end of a loop iteration etc)245246 .. sourcecode:: jinja247248 {% for items in seq %}249 {% for item in items %}250 <li>{{ item|e }}</li>251 {% endfor %}252 {{ flush() }}253 {% endfor %}254255 *new in Jinja 1.1*256238Loops239=====240241To iterate over a sequence, you can use the `for` loop. It basically looks like a
242 unmodified lines
484 {% endmacro %}485486 {{ show_dialog('Warning', 'something went wrong i guess') }}487488*Improvements in Jinja 1.1*:489490 Starting with Jinja 1.1 it's possible to use optional parentheses491 around the macro arguments:492493 .. sourcecode:: html+jinja494495 {% macro foo(a, b) %}496 ...497 {% endmacro %}498499 Additionally extra arguments passed to the macro end up in the500 special variable `varargs`. So you can have a macro like this:501502 .. sourcecode:: html+jinja503504 {% macro make_list() %}505 {% if varargs %}506 <ul>507 {% for item in varargs %}508 <li>{{ item|e }}</li>509 {% endfor %}510 </ul>511 {% endif %}512 {% endmacro %}513514 {{ make_list("John", "Jane", "Marcus", "Heinrich") }}515516 If a macro parameter is called `varargs` the additional extra517 arguments are not accessible.518519520Inheritance521===========522523The most powerful part of Jinja is template inheritance. Template inheritance
179 unmodified lines
703The variable ``angryname`` just exists inside the macro, not outside it.704705Defined macros appear on the context as variables. Because of this, they are706affected by the scoping too. A macro defined inside of a macro is just available694in those two macros (the macro itself and the macro it's defined in). For `set`695and `macro` two additional rules exist: If a macro is defined in an extended696template but outside of a visible block (thus outside of any block) will be697available in all blocks below. This allows you to use `include` statements to698load often used macros at once.707in those two macros (the macro itself and the macro it's defined in).708709Template Globals710================711712A special threatment exists for template code outside of visible blocks in713child templates. This code will be executed **before** the layout template714code. Thus it can be used to propagate values back to the layout template or715import macros from templates for rendering.716717Such code can output data but it won't appear in the final rendering. So no718additional whitespace will pollute the template.719720Because this code is executed before the actual layout template code it's721possible that the layout code overrides some of those variables. Usually722this is not a problem because of different variable names but it can be723a problem if you plan to specify default values.724725In that case you have to test if the variable is not defined before setting726it:727728.. sourcecode:: jinja729730 {% if not page_title %}731 {% set page_title = 'Default Page Title' %}732 {% endif %}733734You can of course also use the `|default` filter.735736.. admonition:: Explanation737738 This template stored as `a.html`:739740 .. sourcecode:: html+jinja741742 <title>{{ title|default('Untitled') }}</title>743 <body>{% block body %}{% endblock %}744745 ...and this child template stored as `b.html`:746747 .. sourcecode:: html+jinja748749 {% extends 'a.html' %}750 {% include 'macros.tmpl' %}751 {% set title = 'My Page' %}752 {% block body %}{{ wrap(42) }}{% endblock %}753754 ...and this code in `macros.tmpl`:755756 .. sourcecode:: html+jinja757758 {% macro wrap(text) %}759 [{{ text }}]760 {% endmacro %}761762 ..will translate to something with the same semantics as this (just763 that the value is not stored in a variable):764765 .. sourcecode:: html+jinja766767 {% filter capture('captured', true) %}768 {% macro wrap(text) %}769 [{{ text }}]770 {% endmacro %}771 {% set title='My Page' %}772 {% endfilter %}773 <title>{{ title|default('Untitled') }}</title>774 <body>775 {{ wrap(42) }}776 </body>777778.. admonition:: Note779780 This implementation was improved in Jinja 1.1. In Jinja 1.0 blocks that781 were not top-level were not propagated to the layout template. This made782 it impossible to use conditional expressions for inclusion in non root783 templates.784785786Undefined Variables787===================788789If you have already worked with python you probably know about the fact that790undefined variables raise an exception. This is different in Jinja. There is a791special value called `undefined` that represents values that do not exist.792707This special variable works complete different from any variables you maybe708know. If you print it using ``{{ variable }}`` it will not appear because it's709literally empty. If you try to iterate over it, it will work. But no items710are returned. Comparing this value to any other value results in `false`.711Even if you compare it to itself:793Depending on the configuration it will behave different.794795In order to check if a value is defined you can use the `defined` test:796797.. sourcecode:: jinja798715 {{ undefined == undefined }}716 will return false. Not even undefined is undefined :)717 Use `is defined` / `is not defined`:799 {{ myvariable is not defined }}800 will return true if the variable does not exist.801719 {{ undefined is not defined }}720 will return true.802`SilentUndefined`:803722There are also some additional rules regarding this special value. Any723mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand724as result:804 The silent `undefined` is the default behavior. The `undefined` object works805 complete different from any variables you maybe know. If you print it806 using ``{{ variable }}`` it will not appear because it's literally empty.807 If you try to iterate over it, it will work. But no items are returned.808726.. sourcecode:: jinja809 In order to check if a value is defined you can use the `defined` test:810728 {{ undefined + "foo" }}729 returns "foo"811 There are also some additional rules regarding this special value. Any812 mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand813 as result:814731 {{ undefined - 42 }}732 returns 42. Note: not -42!815 .. sourcecode:: jinja816734In any expression `undefined` evaluates to `false`. It has no length, all735attribute calls return undefined, calling too:817 {{ undefined + "foo" }}818 returns "foo"819737.. sourcecode:: jinja820 {{ undefined - 42 }}821 returns 42. Note: not -42!822739 {{ undefined.attribute().attribute_too[42] }}740 still returns `undefined`.823 In any expression `undefined` evaluates to `false`. It has no length, all824 attribute calls return undefined, calling too:825742Starting with Jinja 1.1 it's possible to control the `undefined` behavior743in the Jinja environment, thus on the application side. If you receive744a `TemplateRuntimeError` when operating on an undefined variable the745environment was created with `silent` disabled.826 .. sourcecode:: jinja827747In a non silent environment the error you get tells you the line number748and the name of the variable / attribute which could not be found.828 {{ undefined.attribute().attribute_too[42] }}829 still returns `undefined`.830831`ComplainingUndefined`:832833 Starting with Jinja 1.1 it's possible to replace the default undefined834 object with different values. The other common undefined object which835 comes with Jinja is the `ComplainingUndefined` object.836837 It raises exceptions as soon as you either render it or want to iterate838 over it or try to access attributes etc.839 840841Escaping842========843844Sometimes you might want to add Jinja syntax elements into the template
202 unmodified lines
1047 </div>1048 </div>1049 {% endmacro %}1050960 Called the normal way `caller` will be undefined and thus return nothing961 in silent mode or raise an exception in non silent. But if you call it962 with the new `{% call %}` tag you can pass it some data:1051 Called the normal way `caller` will be undefined, but if you call it1052 using the new `{% call %}` tag you can pass it some data:10531054 .. sourcecode:: html+jinja10551056 {% call dialog('Hello World') %}
35 unmodified lines
modified:docs/src/devintro.txt+16 added
72 unmodified lines
7374There are also some internal functions on the environment used by the template75evaluation code to keep it sandboxed.7677Undefined Values78================7980If a template designer tries to access a not defined value the return value81will be the `undefined_singleton` specified in the environment. The default82one is the `SilentUndefined` which fails in no case. Additionally there is83a special undefined type called the `ComplainingUndefined` which is located84in the `jinja.datastructure` module. It will raise exceptions when compared85with other types, or when rendered.8687Theoretically you can provide your own singleton by subclassing88`AbstractUndefindedType` and creating an instance of it using `make_undefined`89(both located in `jinja.datastructure`) but those two types should cover90the basic use cases. The `Undefined` object in that module exists for91backwards compatibility and is an alias for `SilentUndefined`.9293Automatic Escaping94==================9596Jinja provides a way for automatic escaping, but we do not recommend using it.
65 unmodified lines
modified:docs/src/streaming.txt+46 added-72 removed
8 unmodified lines
9If you for example generate a file with a couple of megabytes you may want10to pass the stream to the WSGI interface in order to keep the amount of11memory used low and deliver the output to the browser as fast as possible.1213The streaming works quite simple. Whenever an item is returned by the14internal generator it's passed to a `TemplateStream` which buffers 40 events15before yielding them. Because WSGI usually slows down on too many flushings16this is the integrated solution for this problem. The template designer17can further control that behavior by placing a ``{{ flush() }}`` call in18the template. Whenever the `TemplateStream` encounters an object marked as19flushable it stops buffering and yields the item.13The streaming interface is straightforward. Instead of using `render()` you14can call `stream()` which does pretty much the same but doesn't return a15string but a `TemplateStream`:1621Note that some constructs are not part of the stream. For example blocks22that are rendered using ``{{ super() }}`` are yielded as one flushable item.17.. sourcecode:: pycon1824This restriction exists because template designers may want to operate on25the return value of a macro, block etc.19 >>> tmpl = env.from_string("<ul>{% for item in seq %}\n <li>{{ loop.index "20 ... "}} - {{ item }}</li>\n{%- endfor %}</ul>")21 >>> stream = tmpl.stream(seq=range(4))22 >>> stream.next()23 '<ul>'24 >>> stream.next()25 u'\n <li>1 - 0</li>'26 >>> stream.next()27 u'\n <li>2 - 1</li>'28 >>> stream.next()29 u'\n <li>3 - 2</li>'30 >>> stream.next()31 u'\n <li>4 - 3</li>'32 >>> stream.next()33 '</ul>'3427The following constructs yield their subcontents as one event: ``blocks``28that are not the current one (eg, blocks called using ``{{ super() }}``),29macros, filtered sections.35As you can see each iteration is threated as template event here. But also36other tags trigger events. Basically every tag yields one event, the37`print` tag too. The only exception is the variable substitution syntax which38is inserted into the template text data.3931The TemplateStream32==================40Because some protocols like `WSGI` flush after each iteration if passed as41response iterable it's better to buffer some events internally. You can do42this by enable buffering using `enable_buffering` and passing it the buffer43size which must be greater than one:4434You can get a new `TemplateStream` by calling the `stream()` function on35a template like you would do for rendering. The `TemplateStream` behaves36like a normal generator/iterator. However, as long as the stream is not37started you can modify the buffer threshold. Once the stream started38streaming it looses the `threshold` attribute.3940Explicit flushing:4145.. sourcecode:: pycon4644 >>> tmpl = evironment.from_string("<ul>{% for item in seq %}"45 ... "<li>{{ item }}</li>{{ flush() }}{% endfor %}</ul>")46 >>> s = tmpl.stream(seq=range(3))47 >>> s.next()48 u'<ul><li>0</li>'49 >>> s.next()50 u'<li>1</li>'51 >>> s.next()52 u'<li>2</li>'53 >>> s.next()54 u'</ul>'55 >>> 47 >>> stream.enable_buffering(size=3)48 >>> stream.next()49 u'<ul>\n <li>1 - 0</li>\n <li>2 - 1</li>'50 >>> stream.next()51 u'\n <li>3 - 2</li>\n <li>4 - 3</li></ul>'5257Implicit flushing after 6 events:53This will buffer 3 events before yielding. Disabling buffering works using the54`disable_buffering` method. You can enable and disable buffering on the fly also55if you have already iterated over that stream. To check if you are in buffered56or unbuffered mode you can use the `.buffered` property:5758.. sourcecode:: pycon5961 >>> tmpl = environment.from_string("<ul>{% for item in seq %}"62 ... "<li>{{ item }}</li>{% endfor %}</ul>")63 >>> s = tmpl.stream(seq=range(6))64 >>> s.threshold = 665 >>> s.next()66 u'<ul><li>0</li><li>1'67 >>> s.next()68 u'</li><li>2</li><li>3'69 >>> s.next()70 u'</li><li>4</li><li>5'71 >>> s.next()72 u'</li></ul>'7374General `TemplateStream` behavior:7576.. sourcecode:: pycon7778 >>> s = tmpl.stream(seq=range(6))79 >>> s.started60 >>> stream.buffered61 False81 >>> s.threshold82 4083 >>> s.next()84 u'<ul><li>0</li><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>'85 >>> s.started62 >>> stream.enable_buffering(20)63 >>> stream.buffered64 True87 >>> s.threshold88 Traceback (most recent call last):89 File "<stdin>", line 1, in <module>90 AttributeError: 'TemplateStream' object has no attribute 'threshold'65 >>> stream.disable_buffering()66 >>> stream.buffered67 False6869.. admonition:: Note7093Stream Control94==============71 Jinja uses buffering internally for some constructs like macros. A macro72 call is yielded as one event, independently of the internal structure.7396The stream control is designed so that it's completely transparent. When used97in non stream mode the invisible flush tokens disappear. In order to flush98the stream after calling a specific function all you have to do is to wrap99the return value in a `jinja.datastructure.Flush` object. This however100bypasses the automatic filtering system and converts the value to unicode.74 The same applies to recursive for loops and `{% filter %}` tags.
modified:jinja/translators/python.py+241 added-102 removed
14 unmodified lines
1516 It also adds debug symbols used by the traceback toolkit implemented17 in `jinja.utils`.1819 Implementation Details20 ======================2122 Some of the semantics are handled directly in the translator in order23 to speed up the parsing process. For example the semantics for the24 `is` operator are handled here, changing this would require and25 additional traversing of the node tree in the parser. Thus the actual26 translation process can raise a `TemplateSyntaxError` too.2728 It might sound strange but the translator tries to keep the generated29 code readable as much as possible. This simplifies debugging the Jinja30 core a lot. The additional processing overhead is just relevant for31 the translation process, the additional comments and whitespace won't32 appear in the saved bytecode.3334 :copyright: 2007 by Armin Ronacher.35 :license: BSD, see LICENSE for more details.36"""37import re
12 unmodified lines
50#: regular expression for the debug symbols51_debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '52 r'lineno=(?P<lineno>\d+)\)$')5354# For Python2.3 compatibiilty55try:56 set57except NameError:58 from sets import Set as set5960# For Python 2.3/2.4 compatibility61try:62 GeneratorExit63except NameError:64 class GeneratorExit(Exception):44 """For python2.3/python2.4 compatibility"""65 pass664667# For Pythons without conditional expressions68try:48 set49except NameError:50 from sets import Set as set69 exec '0 if 0 else 0'70 have_conditional_expr = True71except SyntaxError:72 have_conditional_expr = False737453def _to_tuple(args):54 """55 Return a tuple repr without nested repr.56 """57 return '(%s%s)' % (58 ', '.join(args),59 len(args) == 1 and ',' or ''60 )616275class Template(object):76 """77 Represents a finished template.78 """
93 unmodified lines
172 self.constants = {173 'true': 'True',174 'false': 'False',175 'none': 'None',164 'undefined': 'Undefined'176 'undefined': 'undefined_singleton'177 }178179 #: bind the nodes to the callback functions. There are180 #: some missing! A few are specified in the `unhandled`
3 unmodified lines
184 self.handlers = {185 # jinja nodes186 nodes.Template: self.handle_template,187 nodes.Text: self.handle_template_text,188 nodes.DynamicText: self.handle_dynamic_text,189 nodes.NodeList: self.handle_node_list,190 nodes.ForLoop: self.handle_for_loop,191 nodes.IfCondition: self.handle_if_condition,192 nodes.Cycle: self.handle_cycle,
73 unmodified lines
266 first line.267 """268 return (' ' * (self.indention * 4)) + text269270 def to_tuple(self, args):271 """272 Return a tuple repr without nested repr.273 """274 return '(%s%s)' % (275 ', '.join(args),276 len(args) == 1 and ',' or ''277 )278279 def nodeinfo(self, node, force=False):280 """281 Return a comment that helds the node informations or None282 if there is no need to add a debug comment.
30 unmodified lines
313 'for filters', n.lineno,314 n.filename)315 filters.append('(%r, %s)' % (316 n.node.name,295 _to_tuple(args)317 self.to_tuple(args)318 ))319 elif n.__class__ is ast.Name:320 filters.append('(%r, ())' % n.name)321 else:322 raise TemplateSyntaxError('invalid filter. filter must be a '323 'hardcoded function name from the '324 'filter namespace',325 n.lineno, n.filename)326 self.used_shortcuts.add('apply_filters')304 return 'apply_filters(%s, context, %s)' % (s, _to_tuple(filters))327 return 'apply_filters(%s, context, %s)' % (s, self.to_tuple(filters))328329 def handle_node(self, node):330 """331 Handle one node. Resolves the correct callback functions defined
13 unmodified lines
345 def reset(self):346 """347 Reset translation variables such as indention or cycle id348 """349 #: current level of indention350 self.indention = 0351 #: each {% cycle %} tag has a unique ID which increments352 #: automatically for each tag.353 self.last_cycle_id = 0354 #: set of used shortcuts jinja has to make local automatically355 self.used_shortcuts = set(['undefined_singleton'])356 #: set of used datastructures jinja has to import357 self.used_data_structures = set()358 #: set of used utils jinja has to import359 self.used_utils = set()360 #: flags for runtime error361 self.require_runtime_error = False362363 def translate(self):364 """365 Translate the node defined in the constructor after
16 unmodified lines
382 # if there is a parent template we parse the parent template and383 # update the blocks there. Once this is done we drop the current384 # template in favor of the new one. Do that until we found the385 # root template.352 requirements_todo = []386 parent = None387 overwrites = {}388 blocks = {}389 requirements = []390 outer_filename = node.filename or '<template>'391392 # this set is required in order to not add blocks to the block393 # dict a second time if they were not overridden in one template394 # in the template chain.395 already_registered_block = set()396397 while node.extends is not None:358 # handle all requirements but not those from the359 # root template. The root template renders everything so360 # there is no need for additional requirements361 if node not in requirements_todo:362 requirements_todo.append(node)398 # the direct child nodes in a template that are not blocks399 # are processed as template globals, thus executed *before*400 # the master layout template is loaded. This can be used401 # for further processing. The output of those nodes does402 # not appear in the final template.403 requirements += [child for child in node.getChildNodes()404 if child.__class__ not in (nodes.Text,405 nodes.Block, nodes.Extends)]406407 # load the template we inherit from and add not known blocks408 parent = self.environment.loader.parse(node.extends.template,409 node.filename)
5 unmodified lines
415 for n in get_nodes(nodes.Block, parent):416 # an overwritten block for the parent template. handle that417 # override in the template and register it in the deferred418 # block dict.376 if n.name in overwrites:419 if n.name in overwrites and not n in already_registered_block:420 blocks.setdefault(n.name, []).append(n.clone())421 n.replace(overwrites[n.name])422 already_registered_block.add(n)423 # make the parent node the new node424 node = parent425382 # look up requirements383 requirements = []384 for req in requirements_todo:385 for n in req:386 if n.__class__ in (nodes.Set, nodes.Macro, nodes.Include):387 requirements.append(n)388389 # aliases boilerplate390 aliases = ['%s = environment.%s' % (item, item) for item in391 ['get_attribute', 'perform_test', 'apply_filters',392 'call_function', 'call_function_simple', 'finish_var']]393394 # bootstrapping code395 lines = [396 '# Essential imports\n'397 'from __future__ import division\n'398 'from jinja.datastructure import Undefined, LoopContext, '399 'CycleContext, SuperBlock\n'400 'from jinja.utils import buffereater\n'401 'from jinja.exceptions import TemplateRuntimeError\n\n'402 '# Local aliases for some speedup\n'403 '%s\n'404 '__name__ = %r\n\n'405 'def generate(context):\n'406 ' assert environment is context.environment\n'407 ' ctx_push = context.push\n'408 ' ctx_pop = context.pop' % (409 '\n'.join(aliases),410 node.filename411 )412 ]413414 # we have requirements? add them here.415 body_lines = []426 # handle requirements code427 if requirements:428 requirement_lines = [429 'def bootstrap(context):',430 ' ctx_push = context.push',431 ' ctx_pop = context.pop'432 ]433 has_requirements = False434 for n in requirements:418 body_lines.append(self.handle_node(n))435 requirement_lines.append(self.handle_node(n))436 requirement_lines.append(' if 0: yield None\n')437420 # the template body421 body_lines.extend([self.handle_node(n) for n in node])438 # handle body in order to get the used shortcuts439 body_lines = [self.handle_node(n) for n in node]440423 # add body lines and "generator hook"424 lines.extend(body_lines)425 lines.append(' if 0: yield None')426427 # add the missing blocks441 # same for blocks in callables442 block_lines = []443 block_items = blocks.items()444 block_items.sort()445 dict_lines = []446 for name, items in block_items:
1 unmodified line
448 for idx, item in enumerate(items):449 # ensure that the indention is correct450 self.indention = 1451 func_name = 'block_%s_%s' % (name, idx)452 data = self.handle_block(item, idx + 1)453 # blocks with data454 if data:437 lines.extend([438 '\ndef %s(context):' % func_name,439 ' ctx_push = context.push',440 ' ctx_pop = context.pop',441 ' if 0: yield None'442 ])443 lines.append(self.indent(self.nodeinfo(item, True)))444 lines.append(self.handle_block(item, idx + 1))445 tmp.append('buffereater(%s)' % func_name)455 block_lines.extend([456 'def %s(context):' % func_name,457 ' ctx_push = context.push',458 ' ctx_pop = context.pop',459 self.indent(self.nodeinfo(item, True)),460 data,461 ' if 0: yield None\n'462 ])463 tmp.append('buffereater(%s)' % func_name)464 self.used_utils.add('buffereater')465 # blocks without data, can default to something466 # from utils467 else:468 tmp.append('empty_block')469 self.used_utils.add('empty_block')470 dict_lines.append(' %r: %s' % (471 str(name),448 _to_tuple(tmp)472 self.to_tuple(tmp)473 ))474475 # aliases boilerplate476 aliases = ['%s = environment.%s' % (item, item) for item in477 ['get_attribute', 'perform_test', 'apply_filters',478 'call_function', 'call_function_simple', 'finish_var',479 'undefined_singleton'] if item in self.used_shortcuts]480481 # bootstrapping code482 lines = ['# Essential imports', 'from __future__ import division']483 if self.used_utils:484 lines.append('from jinja.utils import %s' % ', '.join(self.used_utils))485 if self.require_runtime_error:486 lines.append('from jinja.exceptions import TemplateRuntimeError')487 if self.used_data_structures:488 lines.append('from jinja.datastructure import %s' % ', '.489 join(self.used_data_structures))490 lines.extend([491 '\n# Aliases for some speedup\n'492 '%s\n\n'493 '# Name for disabled debugging\n'494 '__name__ = %r\n\n'495 'def generate(context):\n'496 ' assert environment is context.environment\n'497 ' ctx_push = context.push\n'498 ' ctx_pop = context.pop' % (499 '\n'.join([500 '%s = environment.%s' % (item, item) for item in501 ['get_attribute', 'perform_test', 'apply_filters',502 'call_function', 'call_function_simple', 'finish_var',503 'undefined_singleton'] if item in self.used_shortcuts504 ]),505 outer_filename506 )507 ])508509 # the template body510 if requirements:511 lines.append(' for item in bootstrap(context): pass')512 lines.extend(body_lines)513 lines.append(' if 0: yield None\n')514515 # now write the bootstrapping (requirements) core if there is one516 if requirements:517 lines.append('# Bootstrapping code')518 lines.extend(requirement_lines)519520 # blocks must always be defined. even if it's empty. some521 # features depend on it453 lines.append('\n# Block mapping and debug information')522 if block_lines:523 lines.append('# Superable blocks')524 lines.extend(block_lines)525 lines.append('# Block mapping')526 if dict_lines:455 lines.append('blocks = {\n%s\n}' % ',\n'.join(dict_lines))527 lines.append('blocks = {\n%s\n}\n' % ',\n'.join(dict_lines))528 else:457 lines.append('blocks = {}')529 lines.append('blocks = {}\n')530531 # now get the real source lines and map the debugging symbols532 debug_mapping = []533 file_mapping = {}
6 unmodified lines
540 m = _debug_re.search(line)541 if m is not None:542 d = m.groupdict()543 filename = d['filename'] or None544 if isinstance(filename, unicode):545 filename = filename.encode('utf-8')546 if filename in file_mapping:547 file_id = file_mapping[filename]548 else:549 file_id = file_mapping[filename] = 'F%d' % \
9 unmodified lines
559 else:560 result.append(line)561562 # now print file mapping and debug info563 result.append('\n# Debug Information')564 file_mapping = file_mapping.items()565 file_mapping.sort(lambda a, b: cmp(a[1], b[1]))566 for filename, file_id in file_mapping:567 result.append('%s = %r' % (file_id, filename))493 result.append('debug_info = [%s]' % ', '.join(debug_mapping))568 result.append('debug_info = %s' % self.to_tuple(debug_mapping))569 return '\n'.join(result)570571 def handle_template_text(self, node):572 """
7 unmodified lines
580 data = node.text581 return self.indent(self.nodeinfo(node)) + '\n' +\582 self.indent('yield %r' % data)583584 def handle_dynamic_text(self, node):585 """586 Like `handle_template_text` but for nodes of the type587 `DynamicText`.588 """589 buf = []590 write = lambda x: buf.append(self.indent(x))591 self.used_shortcuts.add('finish_var')592593 write(self.nodeinfo(node))594 write('yield %r %% (' % node.format_string)595 self.indention += 1596 for var in node.variables:597 write(self.nodeinfo(var))598 write('finish_var(%s, context)' % self.handle_node(var.variable) + ',')599 self.indention -= 1600 write(')')601602 return '\n'.join(buf)603604 def handle_node_list(self, node):605 """606 In some situations we might have a node list. It's just607 a collection of multiple statements.
9 unmodified lines
617 """618 Handle a for loop. Pretty basic, just that we give the else619 clause a different behavior.620 """621 self.used_data_structures.add('LoopContext')622 buf = []623 write = lambda x: buf.append(self.indent(x))624 write(self.nodeinfo(node))625 write('ctx_push()')626627 # recursive loops628 if node.recursive:533 write('def forloop(seq):')629 write('def loop(seq):')630 self.indention += 1631 write('for %s in context[\'loop\'].push(seq):' %632 self.handle_node(node.item),633 )
28 unmodified lines
662 write('context[\'loop\'].pop()')663 write('if 0: yield None')664 self.indention -= 1665 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '570 'buffereater(forloop))')571 write('for item in forloop(%s):' % self.handle_node(node.seq))666 'buffereater(loop))')667 self.used_utils.add('buffereater')668 write('for item in loop(%s):' % self.handle_node(node.seq))669 self.indention += 1670 write('yield item')671 self.indention -= 1672
27 unmodified lines
700 def handle_cycle(self, node):701 """702 Handle the cycle tag.703 """704 self.used_data_structures.add('CycleContext')705 name = '::cycle_%x' % self.last_cycle_id706 self.last_cycle_id += 1707 buf = []708 write = lambda x: buf.append(self.indent(x))
3 unmodified lines
712 write(self.nodeinfo(node))713 if node.seq.__class__ in (ast.Tuple, ast.List):714 write('context.current[%r] = CycleContext(%s)' % (715 name,618 _to_tuple([self.handle_node(n) for n in node.seq.nodes])716 self.to_tuple([self.handle_node(n) for n in node.seq.nodes])717 ))718 hardcoded = True719 else:720 write('context.current[%r] = CycleContext()' % name)721 hardcoded = False722 self.indention -= 1723724 self.used_shortcuts.add('finish_var')725 if hardcoded:726 write('yield finish_var(context.current[%r].cycle(), '727 'context)' % name)728 else:
8 unmodified lines
737 def handle_print(self, node):738 """739 Handle a print statement.740 """741 self.used_shortcuts.add('finish_var')742 return self.indent(self.nodeinfo(node)) + '\n' +\743 self.indent('yield finish_var(%s, context)' %744 self.handle_node(node.variable))745
20 unmodified lines
766767 # collect macro arguments768 arg_items = []769 caller_overridden = False770771 # if we have conditional expressions available in that python772 # build (for example cpython > 2.4) we can use them, they773 # will perform slightly better.774 if have_conditional_expr:775 arg_tmpl = '\'%(name)s\': args[%(pos)d] if argcount > %(pos)d ' \776 'else %(default)s'777 # otherwise go with the and/or tuple hack:778 else:779 arg_tmpl = '\'%(name)s\': (argcount > %(pos)d and '\780 '(args[%(pos)d],) or (%(default)s,))[0]'781782 if node.arguments:783 varargs_init = '\'varargs\': args[%d:]' % len(node.arguments)784 write('argcount = len(args)')785 for idx, (name, n) in enumerate(node.arguments):673 arg_items.append('\'%s\': (argcount > %d and (args[%d],) '674 'or (%s,))[0]' % (675 name,676 idx,677 idx,678 n is None and 'Undefined' or self.handle_node(n)679 ))786 arg_items.append(arg_tmpl % {787 'name': name,788 'pos': idx,789 'default': n is None and 'undefined_singleton' or790 self.handle_node(n)791 })792 if name == 'caller':793 caller_overridden = True794 elif name == 'varargs':795 varargs_init = None796 else:797 varargs_init = '\'varargs\': args'798799 if caller_overridden:800 write('kw.pop(\'caller\', None)')801 else:685 arg_items.append('\'caller\': kw.pop(\'caller\', Undefined)')686 write('ctx_push({%s})' % ', '.join(arg_items))802 arg_items.append('\'caller\': kw.pop(\'caller\', undefined_singleton)')803 if varargs_init:804 arg_items.append(varargs_init)805806 write('ctx_push({%s})' % ',\n '.join([807 idx and self.indent(item) or item for idx, item808 in enumerate(arg_items)809 ]))810811 # disallow any keyword arguments812 write('if kw:')813 self.indention += 1814 write('raise TemplateRuntimeError(\'%s got an unexpected keyword '815 'argument %%r\' %% iter(kw).next())' % node.name)816 self.require_runtime_error = True817 self.indention -= 1818819 write(self.nodeinfo(node.body))696 buf.append(self.handle_node(node.body))820 data = self.handle_node(node.body)821 if data:822 buf.append(data)823 write('ctx_pop()')824 write('if 0: yield None')825 self.indention -= 1826 buf.append(self.indent('context[%r] = buffereater(macro)' %827 node.name))828 self.used_utils.add('buffereater')829830 return '\n'.join(buf)831832 def handle_call(self, node):
5 unmodified lines
838839 write('def call(**kwargs):')840 self.indention += 1841 write('ctx_push(kwargs)')715 buf.append(self.handle_node(node.body))842 data = self.handle_node(node.body)843 if data:844 buf.append(data)845 write('ctx_pop()')846 write('if 0: yield None')847 self.indention -= 1848 write('yield ' + self.handle_call_func(node.expr,849 {'caller': 'buffereater(call)'}))850 self.used_utils.add('buffereater')851852 return '\n'.join(buf)853854 def handle_set(self, node):
18 unmodified lines
873 write('def filtered():')874 self.indention += 1875 write('ctx_push()')876 write(self.nodeinfo(node.body))747 buf.append(self.handle_node(node.body))877 data = self.handle_node(node.body)878 if data:879 buf.append(data)880 write('ctx_pop()')881 write('if 0: yield None')882 self.indention -= 1883 write('yield %s' % self.filter('buffereater(filtered)()',884 node.filters))885 self.used_utils.add('buffereater')886 return '\n'.join(buf)887888 def handle_block(self, node, level=0):889 """
4 unmodified lines
894 rv = self.handle_node(node.body)895 if not rv:896 return ''897898 self.used_data_structures.add('SuperBlock')899 buf = []900 write = lambda x: buf.append(self.indent(x))901902 write(self.nodeinfo(node))
1 unmodified line
904 str(node.name),905 level906 ))907 write(self.nodeinfo(node.body))774 buf.append(self.handle_node(node.body))908 buf.append(rv)909 write('ctx_pop()')910 return '\n'.join(buf)911912 def handle_include(self, node):
87 unmodified lines
1000 else:1001 raise TemplateSyntaxError('is operator requires a test name'1002 ' as operand', node.lineno,1003 node.filename)1004 self.used_shortcuts.add('perform_test')1005 return 'perform_test(context, %r, %s, %s, %s)' % (1006 name,872 _to_tuple(args),1007 self.to_tuple(args),1008 self.handle_node(node.expr),1009 node.ops[0][0] == 'is not'1010 )1011
27 unmodified lines
1039 return '%s[%s]' % (1040 self.handle_node(node.expr),1041 self.handle_node(node.subs[0])1042 )1043 self.used_shortcuts.add('get_attribute')1044 return 'get_attribute(%s, %s)' % (1045 self.handle_node(node.expr),1046 self.handle_node(node.subs[0])1047 )
1 unmodified line
1049 def handle_getattr(self, node):1050 """1051 Handle hardcoded attribute access.1052 """1053 self.used_shortcuts.add('get_attribute')1054 return 'get_attribute(%s, %r)' % (1055 self.handle_node(node.expr),1056 node.attrname1057 )
1 unmodified line
1059 def handle_ass_tuple(self, node):1060 """1061 Tuple unpacking loops.1062 """926 return _to_tuple([self.handle_node(n) for n in node.nodes])1063 return self.to_tuple([self.handle_node(n) for n in node.nodes])10641065 def handle_bitor(self, node):1066 """1067 We use the pipe operator for filtering.
16 unmodified lines
1084 kwargs[arg.name] = self.handle_node(arg.expr)1085 else:1086 args.append(self.handle_node(arg))1087 if extra_kwargs:951 kwargs.update(extra_kwargs) 1088 kwargs.update(extra_kwargs)1089 if not (args or kwargs or star_args or dstar_args or extra_kwargs):1090 self.used_shortcuts.add('call_function_simple')1091 return 'call_function_simple(%s, context)' % \1092 self.handle_node(node.node)1093 self.used_shortcuts.add('call_function')1094 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (1095 self.handle_node(node.node),957 _to_tuple(args),1096 self.to_tuple(args),1097 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),1098 star_args,1099 dstar_args1100 )
144 unmodified lines
modified:jinja/_native.py+3 added-6 removed
12 unmodified lines
13 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred, Undefined17from jinja.exceptions import TemplateRuntimeError171819class BaseContext(object):2022 def __init__(self, silent, globals, initial):23 self._silent = silent21 def __init__(self, undefined_singleton, globals, initial):22 self._undefined_singleton = undefined_singleton23 self.current = current = {}24 self.stack = [globals, initial, current]25 self._push = self.stack.append26 self._pop = self.stack.pop
36 unmodified lines
63 self.initial[name] = rv64 else:65 d[name] = rv66 return rv68 if self._silent:69 return Undefined70 raise TemplateRuntimeError('%r is not defined' % name)67 return self._undefined_singleton6869 def __setitem__(self, name, value):70 """71 Set a variable in the outermost layer.
24 unmodified lines
modified:jinja/_speedups.c+38 added-127 removed
16 unmodified lines
17#include <Python.h>18#include <structmember.h>1920/* Set by init_constants to real values */21static PyObject *Undefined, *Deferred, *TemplateRuntimeError;22static Py_UNICODE *amp, *lt, *gt, *qt;21static PyObject *Deferred;2223/**24 * Internal struct used by BaseContext to store the25 * stacked namespaces.
11 unmodified lines
37 struct StackLayer *globals; /* the dict for the globals */38 struct StackLayer *initial; /* initial values */39 struct StackLayer *current; /* current values */40 long stacksize; /* current size of the stack */42 int silent; /* boolean value for silent failure */41 PyObject *undefined_singleton; /* the singleton returned on missing values */42} BaseContext;4344/**45 * Called by init_speedups in order to retrieve references
4 unmodified lines
50{51 PyObject *datastructure = PyImport_ImportModule("jinja.datastructure");52 if (!datastructure)53 return 0;55 PyObject *exceptions = PyImport_ImportModule("jinja.exceptions");56 if (!exceptions) {57 Py_DECREF(datastructure);58 return 0;59 }60 Undefined = PyObject_GetAttrString(datastructure, "Undefined");54 Deferred = PyObject_GetAttrString(datastructure, "Deferred");62 TemplateRuntimeError = PyObject_GetAttrString(exceptions, "TemplateRuntimeError");6364 amp = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&amp;", 5, NULL))->str;65 lt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&lt;", 4, NULL))->str;66 gt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&gt;", 4, NULL))->str;67 qt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&quot;", 6, NULL))->str;6855 Py_DECREF(datastructure);70 Py_DECREF(exceptions);56 return 1;57}5859/**75 * SGML/XML escape something.76 *77 * XXX: this is awefully slow for non unicode objects because they78 * get converted to unicode first.79 */80static PyObject*81escape(PyObject *self, PyObject *args)82{83 PyUnicodeObject *in, *out;84 Py_UNICODE *outp;85 int i, len;8687 PyObject *text = NULL, *use_quotes = NULL;8889 if (!PyArg_ParseTuple(args, "O|O", &text, &use_quotes))90 return NULL;91 int quotes = use_quotes && PyObject_IsTrue(use_quotes);92 in = (PyUnicodeObject*)PyObject_Unicode(text);93 if (!in)94 return NULL;9596 /* First we need to figure out how long the escaped string will be */97 len = 0;98 for (i = 0; i < in->length; i++) {99 switch (in->str[i]) {100 case '&':101 len += 5;102 break;103 case '"':104 len += quotes ? 6 : 1;105 break;106 case '<':107 case '>':108 len += 4;109 break;110 default:111 len++;112 }113 }114115 /* Do we need to escape anything at all? */116 if (len == in->length)117 return (PyObject*)in;118119 out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, len);120 if (!out) {121 Py_DECREF(in);122 return NULL;123 }124125 outp = out->str;126 for (i = 0; i < in->length; i++) {127 switch (in->str[i]) {128 case '&':129 Py_UNICODE_COPY(outp, amp, 5);130 outp += 5;131 break;132 case '"':133 if (quotes) {134 Py_UNICODE_COPY(outp, qt, 6);135 outp += 6;136 }137 else138 *outp++ = in->str[i];139 break;140 case '<':141 Py_UNICODE_COPY(outp, lt, 4);142 outp += 4;143 break;144 case '>':145 Py_UNICODE_COPY(outp, gt, 4);146 outp += 4;147 break;148 default:149 *outp++ = in->str[i];150 };151 }152153 Py_DECREF(in);154 return (PyObject*)out;155}156157/**60 * Deallocator for BaseContext.61 *62 * Frees the memory for the stack layers before freeing the object.63 */
13 unmodified lines
7778/**79 * Initializes the BaseContext.80 *179 * Like the native python class it takes a flag telling the context180 * to either fail silently with Undefined or raising a TemplateRuntimeError.81 * Like the native python class it takes a reference to the undefined82 * singleton which will be used for undefined values.83 * The other two arguments are the global namespace and the initial84 * namespace which usually contains the values passed to the render85 * function of the template. Both must be dicts.86 */87static int88BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)89{188 PyObject *silent = NULL, *globals = NULL, *initial = NULL;90 PyObject *undefined = NULL, *globals = NULL, *initial = NULL;91190 static char *kwlist[] = {"silent", "globals", "initial", NULL};191 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", kwlist,192 &silent, &globals, &initial))92 if (!PyArg_ParseTuple(args, "OOO", &undefined, &globals, &initial))93 return -1;94 if (!PyDict_Check(globals) || !PyDict_Check(initial)) {95 PyErr_SetString(PyExc_TypeError, "stack layers must be dicts.");96 return -1;97 }98199 self->silent = PyObject_IsTrue(silent);200 if (self->silent == -1)201 return -1;20299 self->current = PyMem_Malloc(sizeof(struct StackLayer));100 self->current->prev = NULL;101 self->current->dict = PyDict_New();102 if (!self->current->dict)
10 unmodified lines
113 self->globals->dict = globals;114 Py_INCREF(globals);115 self->initial->prev = self->globals;116117 self->undefined_singleton = undefined;118 Py_INCREF(undefined);119120 self->stacksize = 3;121 return 0;122}123
121 unmodified lines
245 char *name = NULL;246 int isdeferred;247 struct StackLayer *current = self->current;248 249 /* allow unicode keys as long as they are ascii keys */250 if (PyUnicode_CheckExact(item)) {251 item = PyUnicode_AsASCIIString(item);252 if (!item)253 goto missing;254 }350 if (!PyString_Check(item))255 else if (!PyString_Check(item))256 goto missing;257258 /* disallow access to internal jinja values */259 name = PyString_AS_STRING(item);
31 unmodified lines
291 return result;292 }293294missing:390 if (self->silent) {391 Py_INCREF(Undefined);392 return Undefined;393 }394 if (name)395 PyErr_Format(TemplateRuntimeError, "'%s' is not defined", name);396 else397 PyErr_SetString(TemplateRuntimeError, "value is not a string");398 return NULL;295 Py_INCREF(self->undefined_singleton);296 return self->undefined_singleton;297}298299/**300 * Check if the context contains a given value.
3 unmodified lines
304{305 char *name;306 struct StackLayer *current = self->current;307308 /* allow unicode objects as keys as long as they are ASCII */309 if (PyUnicode_CheckExact(item)) {310 item = PyUnicode_AsASCIIString(item);311 if (!item)312 return 0;313 }410 if (!PyString_Check(item))314 else if (!PyString_Check(item))315 return 0;316317 name = PyString_AS_STRING(item);318 if (name[0] && name[0] == ':' && name[1] == ':')
16 unmodified lines
335 */336static int337BaseContext_setitem(BaseContext *self, PyObject *item, PyObject *value)338{435 if (!PyString_Check(item)) {436 PyErr_SetString(PyExc_TypeError, "expected string argument");437 return -1;339 /* allow unicode objects as keys as long as they are ASCII */340 if (PyUnicode_CheckExact(item)) {341 item = PyUnicode_AsASCIIString(item);342 if (!item) {343 PyErr_Clear();344 goto error;345 }346 }347 else if (!PyString_Check(item))348 goto error;349 if (!value)350 return PyDict_DelItem(self->current->dict, item);351 return PyDict_SetItem(self->current->dict, item, value);352353error:354 PyErr_SetString(PyExc_TypeError, "expected string argument");355 return -1;356}357358/**359 * Size of the stack.
89 unmodified lines
449 PyType_GenericNew /* tp_new */450};451452static PyMethodDef module_methods[] = {539 {"escape", (PyCFunction)escape, METH_VARARGS,540 "escape(s, quotes=False) -> string\n\n"541 "SGML/XML a string."},453 {NULL, NULL, 0, NULL} /* Sentinel */454};455456#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
20 unmodified lines
modified:jinja/datastructure.py+120 added-69 removed
32 unmodified lines
33 f.jinja_unsafe_call = True34 return f353637class UndefinedType(object):37def make_undefined(implementation):38 """39 An object that does not exist.39 Creates an undefined singleton based on a given implementation.40 It performs some tests that make sure the undefined type implements41 everything it should.42 """43 self = object.__new__(implementation)44 self.__reduce__()45 return self464748class AbstractUndefinedType(object):49 """50 Base class for any undefined type.51 """52 __slots__ = ()5354 def __init__(self):55 raise TypeError('cannot create %r instances' %56 self.__class__.__name__)5758 def __setattr__(self, name, value):59 raise AttributeError('%r object has no attribute %r' % (60 self.__class__.__name__,61 name62 ))6364 def __eq__(self, other):65 return self is other6667 def __ne__(self, other):68 return self is not other6970 def __copy__(self):71 return self72 __deepcopy__ = __copy__7374 def __reduce__(self):75 raise TypeError('undefined objects have to provide a __reduce__')767778class SilentUndefinedType(AbstractUndefinedType):79 """80 An object that does not exist.81 """82 __slots__ = ()8384 def __add__(self, other):85 """Any operator returns the operand."""86 return other87 __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __mod__ =\
27 unmodified lines
115 def __unicode__(self):116 """The unicode representation is empty."""117 return u''11882 def __repr__(self):83 """The representation is ``'Undefined'``"""84 return 'Undefined'85119 def __int__(self):120 """Converting `Undefined` to an integer ends up in ``0``"""121 return 0122123 def __float__(self):124 """Converting `Undefined` to an float ends up in ``0.0``"""125 return 0.012694 def __eq__(self, other):95 """`Undefined` is not equal to anything else."""96 return False9798 def __ne__(self, other):99 """`Undefined` is not equal to anything else."""100 return True101127 def __call__(self, *args, **kwargs):128 """Calling `Undefined` returns `Undefined`"""129 return self130106 def __copy__(self):107 """Return a copy."""108 return self131 def __reduce__(self):132 """Helper for pickle."""133 return 'SilentUndefined'134110 def __deepcopy__(self, memo):111 """Return a deepcopy."""112 return self135136class ComplainingUndefinedType(AbstractUndefinedType):137 """138 An object that does not exist.139 """140 __slots__ = ()141142 def __iter__(self):143 """Iterating over `Undefined` returns an empty iterator."""144 if False:145 yield None146147 def __nonzero__(self):148 """`Undefined` is considered boolean `False`"""149 return False150151 def __str__(self):152 """The string representation raises an error."""153 raise TemplateRuntimeError('Undefined object rendered')154155 def __unicode__(self):156 """The unicode representation raises an error."""157 self.__str__()158159 def __call__(self, *args, **kwargs):160 """Calling `Undefined` returns `Undefined`"""161 raise TemplateRuntimeError('Undefined object called')162163 def __reduce__(self):164 """Helper for pickle."""116 return 'Undefined'165 return 'ComplainingUndefined'166167119#: the singleton instance of UndefinedType120Undefined = object.__new__(UndefinedType)168#: the singleton instances for the undefined objects169SilentUndefined = make_undefined(SilentUndefinedType)170ComplainingUndefined = make_undefined(ComplainingUndefinedType)171172#: jinja 1.0 compatibility173Undefined = SilentUndefined174UndefinedType = SilentUndefinedType175176177class FakeTranslator(object):178 """179 Default null translator.180 """
44 unmodified lines
225 template. The autoescape filter can use that.226 """227228175class Flush(TemplateData):176 """177 After a string marked as Flush the stream will stop buffering.178 """179180 jinja_no_finalization = True181182229# import these here because those modules import Deferred and Undefined230# from this module.231try:232 # try to use the c implementation of the base context if available
9 unmodified lines
242 """243244 def __init__(self, *args, **kwargs):245 environment = args[0]200 super(Context, self).__init__(environment.silent,246 super(Context, self).__init__(environment.undefined_singleton,247 environment.globals,248 dict(*args[1:], **kwargs))249 self._translate_func = None250 self.cache = {}
274 unmodified lines
525526527class TemplateStream(object):528 """483 Pass it a template generator and it will buffer a few items484 before yielding them as one item. Useful when working with WSGI485 because a Jinja template yields far too many items per default.486487 The `TemplateStream` class looks for the invisble `Flush`488 markers sent by the template to find out when it should stop489 buffering.529 Wraps a genererator for outputing template streams.530 """531532 def __init__(self, gen):493 self._next = gen.next494 self._threshold = None495 self.threshold = 40533 self._gen = gen534 self._next = gen._next535 self.buffered = False536537 def disable_buffering(self):538 """539 Disable the output buffering.540 """541 self._next = self._gen.next542 self.buffered = False543544 def enable_buffering(self, size=5):545 """546 Enable buffering. Buffer `size` items before547 yielding them.548 """549 if size <= 1:550 raise ValueError('buffer size too small')551 self.buffered = True552553 def buffering_next():554 buf = []555 c_size = 0556 push = buf.append557 next = self._gen.next558559 try:560 while True:561 item = next()562 if item:563 push(item)564 c_size += 1565 if c_size >= size:566 raise StopIteration()567 except StopIteration:568 if not size:569 raise570 return u''.join(buf)571572 self._next = buffering_next573574 def __iter__(self):575 return self576500 def started(self):501 return self._threshold is not None502 started = property(started)503577 def next(self):505 if self._threshold is None:506 self._threshold = t = self.threshold507 del self.threshold508 else:509 t = self._threshold510 buf = []511 size = 0512 push = buf.append513 next = self._next514515 try:516 while True:517 item = next()518 if item:519 push(item)520 size += 1521 if (size and item.__class__ is Flush) or size >= t:522 raise StopIteration()523 except StopIteration:524 pass525 if not size:526 raise StopIteration()527 return u''.join(buf)578 return self._next()
modified:jinja/defaults.py+2 added-3 removed
9 unmodified lines
10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13from jinja.utils import debug_helper, safe_range, generate_lorem_ipsum, \14 watch_changes, flush14 watch_changes151617__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']18
1 unmodified line
20DEFAULT_NAMESPACE = {21 'range': safe_range,22 'debug': debug_helper,23 'lipsum': generate_lorem_ipsum,24 'watchchanges': watch_changes,25 'flush': flush24 'watchchanges': watch_changes25}
modified:jinja/environment.py+22 added-20 removed
10 unmodified lines
11import re12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined, Markup, Context, FakeTranslator15from jinja.datastructure import SilentUndefined, Markup, Context, FakeTranslator16from jinja.utils import collect_translations, get_attribute17from jinja.exceptions import FilterNotFound, TestNotFound, \18 SecurityException, TemplateSyntaxError, TemplateRuntimeError19from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE
27 unmodified lines
47 loader=None,48 filters=None,49 tests=None,50 context_class=Context,51 silent=True,51 undefined_singleton=SilentUndefined,52 friendly_traceback=True):53 """54 Here the possible initialization parameters:55
40 unmodified lines
96 defined.97 `context_class` the context class this template should use.98 See the `Context` documentation for more99 details.100 `silent` set this to `False` if you want to receive101 errors for missing template variables or102 attributes. Defaults to `False`. *new in103 Jinja 1.1*100 `undefined_singleton` The singleton value that is used for missing101 variables. *new in Jinja 1.1*102 `friendly_traceback` Set this to `False` to disable the developer103 friendly traceback rewriting. Whenever an104 runtime or syntax error occours jinja will105 try to make a developer friendly traceback
23 unmodified lines
129 self.filters = filters is None and DEFAULT_FILTERS.copy() or filters130 self.tests = tests is None and DEFAULT_TESTS.copy() or tests131 self.default_filters = default_filters or []132 self.context_class = context_class135 self.silent = silent133 self.undefined_singleton = undefined_singleton134 self.friendly_traceback = friendly_traceback135136 # global namespace137 if namespace is None:
72 unmodified lines
210 def to_unicode(self, value):211 """212 Convert a value to unicode with the rules defined on the environment.213 """216 if value in (None, Undefined):214 # undefined and None expand to ""215 if value in (None, self.undefined_singleton):216 return u''217 # things that are already unicode can pass. As long as nobody218 # does ugly things with the class it works for jinja too219 elif isinstance(value, unicode):220 return value220 else:221 try:222 return unicode(value)223 except UnicodeError:224 return str(value).decode(self.charset, 'ignore')221 # otherwise try to use __unicode__ or decode __str__222 try:223 return unicode(value)224 except UnicodeError:225 return str(value).decode(self.charset, 'ignore')226227 def get_translator(self, context):228 """229 Return the translator for i18n.
61 unmodified lines
291 try:292 return get_attribute(obj, name)293 except (AttributeError, SecurityException):294 pass294 if self.silent:295 return Undefined296 raise TemplateRuntimeError('attribute %r or object %r not defined' % (297 name, obj))295 if obj is self.undefined_singleton:296 return getattr(self.undefined_singleton, name)297 return self.undefined_singleton298299 def get_attributes(self, obj, attributes):300 """301 Get some attributes from an object. If attributes is an
14 unmodified lines
316 if dyn_kwargs is not None:317 kwargs.update(dyn_kwargs)318 if getattr(f, 'jinja_unsafe_call', False) or \319 getattr(f, 'alters_data', False):320 return Undefined320 return self.undefined_singleton321 if getattr(f, 'jinja_context_callable', False):322 args = (self, context) + args323 return f(*args, **kwargs)324
3 unmodified lines
328 fewer logic here we have a bit of redundant code.329 """330 if getattr(f, 'jinja_unsafe_call', False) or \331 getattr(f, 'alters_data', False):332 return Undefined332 return self.undefined_singleton333 if getattr(f, 'jinja_context_callable', False):334 return f(self, context)335 return f()336
2 unmodified lines
339 As long as no write_var function is passed to the template340 evaluator the source generated by the python translator will341 call this function for all variables.342 """343 if value is Undefined or value is None:343 if value is None:344 return u''345 elif value is self.undefined_singleton:346 return unicode(value)347 elif getattr(value, 'jinja_no_finalization', False):348 return value349 val = self.to_unicode(value)350 if self.default_filters:
2 unmodified lines
modified:jinja/filters.py+9 added-14 removed
10 unmodified lines
11import re12from random import choice13from urllib import urlencode, quote14from jinja.utils import urlize, escape15from jinja.datastructure import Undefined, Markup, TemplateData15from jinja.datastructure import Markup, TemplateData16from jinja.exceptions import FilterArgumentError171819try:
93 unmodified lines
113 if isinstance(s, TemplateData):114 return s115 elif hasattr(s, '__html__'):116 return s.__html__()117 #: small speedup117 #: small speedup, do not convert to unicode if we already118 #: have an unicode object.119 if s.__class__ is not unicode:120 s = env.to_unicode(s)121 return e(s, attribute)122 return wrapped
27 unmodified lines
150 if not hasattr(d, 'iteritems'):151 raise TypeError('a dict is required')152 result = []153 for key, value in d.iteritems():153 if value not in (None, Undefined):154 if value not in (None, env.undefined_singleton):155 result.append(u'%s="%s"' % (156 e(env.to_unicode(key)),157 e(env.to_unicode(value), True)158 ))
77 unmodified lines
236237 {{ ''|default('the string was empty', true) }}238 """239 def wrapped(env, context, value):239 if (boolean and not value) or value in (Undefined, None):240 if (boolean and not value) or value in (env.undefined_singleton, None):241 return default_value242 return value243 return wrapped244
69 unmodified lines
314 def wrapped(env, context, seq):315 try:316 return iter(seq).next()317 except StopIteration:317 if env.silent:318 return Undefined319 raise TemplateRuntimeError('%r is empty' % seq)318 return env.undefined_singleton[0]319 return wrapped320321322def do_last():
3 unmodified lines
326 def wrapped(env, context, seq):327 try:328 return iter(_reversed(seq)).next()329 except StopIteration:331 if env.silent:332 return Undefined333 raise TemplateRuntimeError('%r is empty' % seq)330 return env.undefined_singleton[-1]331 return wrapped332333334def do_random():
3 unmodified lines
338 def wrapped(env, context, seq):339 try:340 return choice(seq)341 except IndexError:345 if env.silent:346 return Undefined347 raise TemplateRuntimeError('%r is empty' % seq)342 return env.undefined_singleton[0]343 return wrapped344345346def do_urlencode():
302 unmodified lines
649 raise FilterArgumentError('You can only capture into variables')650 def wrapped(env, context, value):651 context[name] = value652 if clean:658 return Undefined653 return TemplateData()654 return value655 return wrapped656657
196 unmodified lines
modified:jinja/nodes.py+22 added
71 unmodified lines
72 def __repr__(self):73 return 'Text(%r)' % (self.text,)747576class DynamicText(Node):77 """78 Note that represents normal text with string formattings.79 Those are used for texts that contain variables. The attribute80 `variables` contains a list of Print tags and nothing else.81 """8283 def __init__(self, lineno, format_string, variables):84 self.lineno = lineno85 self.format_string = format_string86 self.variables = variables8788 def get_items(self):89 return [self.format_string] + list(self.variables)9091 def __repr__(self):92 return 'DynamicText(%r, %r)' % (93 self.text,94 self.variables95 )969798class NodeList(list, Node):99 """100 A node that stores multiple childnodes.101 """
296 unmodified lines
modified:jinja/parser.py+49 added-7 removed
85 unmodified lines
86 }8788 #: set of directives that are only available in a certain89 #: context.90 self.context_directives = set(['elif', 'else', 'endblock',91 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',92 'endtrans', 'pluralize'90 self.context_directives = set([91 'elif', 'else', 'endblock', 'endfilter', 'endfor', 'endif',92 'endmacro', 'endraw', 'endtrans', 'pluralize'93 ])9495 self.tokenstream = environment.lexer.tokenize(source, filename)96
125 unmodified lines
222 return nodes.Print(lineno, arguments[0])223224 def handle_macro_directive(self, lineno, gen):225 """226 Handle {% macro foo bar, baz %}.226 Handle {% macro foo bar, baz %} as well as227 {% macro foo(bar, baz) %}.228 """229 try:230 macro_name = gen.next()231 except StopIteration:
8 unmodified lines
240 raise TemplateSyntaxError('illegal use of keyword %r '241 'as macro name.' % macro_name[2],242 lineno, self.filename)243244 # make the punctuation around arguments optional245 arg_list = list(gen)246 if arg_list and arg_list[0][1:] == ('operator', '(') and \247 arg_list[-1][1:] == ('operator', ')'):248 arg_list = arg_list[1:-1]249243 ast = self.parse_python(lineno, gen, 'def %s(%%s):pass' %250 ast = self.parse_python(lineno, arg_list, 'def %s(%%s):pass' %251 str(macro_name[2][:-1]))252 body = self.subparse(end_of_macro, True)253 self.close_remaining_block()254
371 unmodified lines
626 tokenstream.627 """628 def finish():629 """Helper function to remove unused nodelists."""630 if data_buffer:631 flush_data_buffer()632 if len(result) == 1:633 return result[0]634 return result635636 def flush_data_buffer():637 """Helper function to write the contents of the buffer638 to the result nodelist."""639 format_string = []640 insertions = []641 for item in data_buffer:642 if item[0] == 'variable':643 p = self.handle_print_directive(*item[1:])644 format_string.append('%s')645 insertions.append(p)646 else:647 format_string.append(item[2].replace('%', '%%'))648 # if we do not have insertions yield it as text node649 if not insertions:650 result.append(nodes.Text(data_buffer[0][1],651 (u''.join(format_string)).replace('%%', '%')))652 # if we do not have any text data we yield some variable nodes653 elif len(insertions) == len(format_string):654 result.extend(insertions)655 # otherwise we go with a dynamic text node656 else:657 result.append(nodes.DynamicText(data_buffer[0][1],658 u''.join(format_string),659 insertions))660 # clear the buffer661 del data_buffer[:]662663 lineno = self.tokenstream.last[0]664 result = nodes.NodeList(lineno)665 data_buffer = []666 for lineno, token, data in self.tokenstream:667 # comments668 if token == 'comment_begin':669 self.tokenstream.drop_until(end_of_comment, True)
1 unmodified line
671 # this token marks the begin or a variable section.672 # parse everything till the end of it.673 elif token == 'variable_begin':674 gen = self.tokenstream.fetch_until(end_of_variable, True)638 result.append(self.directives['print'](lineno, gen))675 data_buffer.append(('variable', lineno, tuple(gen)))676677 # this token marks the start of a block. like for variables678 # just parse everything until the end of the block679 elif token == 'block_begin':680 # if we have something in the buffer we write the681 # data back682 if data_buffer:683 flush_data_buffer()684685 gen = self.tokenstream.fetch_until(end_of_block, True)686 try:687 lineno, token, data = gen.next()688 except StopIteration:
38 unmodified lines
727 # here the only token we should get is "data". all other728 # tokens just exist in block or variable sections. (if the729 # tokenizer is not brocken)730 elif token in 'data':689 result.append(nodes.Text(lineno, data))731 data_buffer.append(('text', lineno, data))732733 # so this should be unreachable code734 else:735 raise AssertionError('unexpected token %r (%r)' % (token,
32 unmodified lines
modified:jinja/tests.py+1 added-2 removed
7 unmodified lines
8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.datastructure import Undefined121314number_re = re.compile(r'^-?\d+(\.\d+)?$')15
27 unmodified lines
43 {% endif %}4445 See also the ``default`` filter.46 """48 return lambda e, c, v: v is not Undefined47 return lambda e, c, v: v is not e.undefined_singleton484950def test_lower():51 """
73 unmodified lines
modified:jinja/utils.py+42 added-31 removed
15 unmodified lines
16import string17from types import MethodType, FunctionType18from compiler.ast import CallFunc, Name, Const19from jinja.nodes import Trans20from jinja.datastructure import Context, Flush20from jinja.datastructure import Context21from jinja.exceptions import SecurityException, TemplateNotFound2223#: the python2.4 version of deque is missing the remove method24#: because a for loop with a lookup for the missing value written25#: in python is slower we just use deque if we have python2.5 or higher26if sys.version_info >= (2, 5):23# the python2.4 version of deque is missing the remove method24# because a for loop with a lookup for the missing value written25# in python is slower we just use deque if we have python2.5 or higher26try:27 from collections import deque28else:28 deque.remove29except (ImportError, AttributeError):30 deque = None3132# support for python 2.3/2.433try:34 set35except NameError:36 from sets import Set as set
14 unmodified lines
5152#: used by from_string as cache53_from_string_env = None545556def escape(s, quote=None):57 """58 SGML/XML escape an unicode object.59 """60 s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")61 if not quote:62 return s63 return s.replace('"', "&quot;")646566def urlize(text, trim_url_limit=None, nofollow=False):67 """68 Converts any URLs in text into clickable links. Works on http://,69 https:// and www. links. Links can have trailing punctuation (periods,
134 unmodified lines
204 return u'\n\n'.join(result)205 return u'\n'.join([u'<p>%s</p>' % escape(x) for x in result])206207195def flush():196 """197 Yield a flush marker.198 """199 return Flush()200201208def watch_changes(env, context, iterable, *attributes):209 """210 Wise replacement for ``{% ifchanged %}``.211 """
31 unmodified lines
243244# python2.4 and lower has a bug regarding joining of broken generators.245# because of the runtime debugging system we have to keep track of the246# number of frames to skip. that's what RUNTIME_EXCEPTION_OFFSET is for.247try:248 _test_singleton = object()249 def _test_gen_bug():250 raise TypeError(_test_singleton)251 yield None252 ''.join(_test_gen_bug())253except TypeError, e:254 if e.args and e.args[0] is _test_singleton:255 capture_generator = u''.join256 RUNTIME_EXCEPTION_OFFSET = 1241if sys.version_info < (2, 5):242 capture_generator = lambda gen: u''.join(tuple(gen))243 RUNTIME_EXCEPTION_OFFSET = 2257 else:258 capture_generator = lambda gen: u''.join(tuple(gen))259 RUNTIME_EXCEPTION_OFFSET = 2260del _test_singleton, _test_gen_bug261245# this should be faster and used in python2.5 and higher246else:247 capture_generator = u''.join248 RUNTIME_EXCEPTION_OFFSET = 1262250263def buffereater(f):264 """265 Used by the python translator to capture output of substreams.266 (macros, filter sections etc)267 """268 def wrapped(*args, **kwargs):257 return Flush(capture_generator(f(*args, **kwargs)))269 return capture_generator(f(*args, **kwargs))270 return wrapped271272273def empty_block(context):274 """275 An empty callable that just returns an empty decorator.276 Used to represent empty blocks.277 """278 if 0: yield None279280281def fake_template_exception(exception, filename, lineno, source,282 context_or_env):283 """284 Raise an exception "in a template". Return a traceback
376 unmodified lines
661 rv = CacheDict(self.capacity)662 rv._mapping = deepcopy(self._mapping)663 rv._queue = deepcopy(self._queue)664 return rv645646647# escaping function. Use this only if you escape unicode648# objects. in all other cases it's likely that the cgi.escape649# function performs better.650try:651 from jinja._speedups import escape652except ImportError:653 from cgi import escape
modified:tests/runtime/bigtable.py+1 added-1 removed
39 unmodified lines
40 have_mako = True41except ImportError:42 have_mako = False4344table = [dict(a='1',b='2',c='3',d='4',e='5',f='6',g='7',h='8',i='9',j='10')44table = [dict(zip('abcdefghij', map(unicode,range(1, 11))))45 for x in range(1000)]4647genshi_tmpl = MarkupTemplate("""48<table xmlns:py="http://genshi.edgewall.org/">
124 unmodified lines
added:tests/runtime/modglobals.py+37 added
1# test file for block super support2import jdebug3from jinja import Environment, DictLoader45env = Environment(loader=DictLoader({6 'a': '''\7<title>{{ title|e }}</title>8<body>9 {% block body %}Default{% endblock %}10</body>11''',12 'b': '''13{% set foo = 42 %}14''',15 'c': '''16{% extends 'a' %}17{% if true %}18 {% set title = "foo" %}19{% endif %}20{% include 'b' %}21{% include 'tools' %}22{% block body %}23 hehe, this comes from b: {{ foo }}2425 Say hello to the former block content:26 {{ say_hello(super()) }}27{% endblock %}28''',29 'tools': '''30{% macro say_hello name -%}31 Hello {{ name }}!32{%- endmacro %}33'''34}))3536tmpl = env.get_template('c')37print tmpl.render()
modified:CHANGES+11 added-2 removed
33 unmodified lines
34- it's now possible to use newlines in string literals3536- developer friendly traceback is now toggleable3738- silent variable name failure is now toggleable38- the variable failure is now pluggable by replacing the undefined39 singleton for an environment instance4041- fixed issue with old-style classes not implementing `__getitem__`42 (thanks to Axel Böhm for discovering that bug)43
24 unmodified lines
6869- You can now use the environment to just tokenize a template. This can70 be useful for syntax highlighting or other purposes.7171- added optional c-implementation of the context baseclass.72- added optional C-implementation of the context baseclass.7374- you can now use optional parentheses around macro defintions. Thus it's75 possible to write ``{% macro foo(a, b, c) %}`` instead of ``{% macro76 foo a, b, c %}``.7778- additional macro arguments now end up in `varargs`.7980- implemented `{% call %}` - unsure if this makes it into the final release.8182- it's not possible to stream templates.838485Version 1.086-----------87(released Mar 23, 2007)88
1 unmodified line
modified:jdebug.py+12 added-1 removed
31 unmodified lines
3233 PythonTranslator.translate = debug_translate343536def p(x, f=None):36def p(x=None, f=None):37 if x is None and f is not None:38 x = e.loader.get_source(f)39 print PythonTranslator(e, Parser(e, x, f).parse()).translate()4041def l(x):42 for item in e.lexer.tokenize(x):43 print '%5s %-20s %r' % item4445if __name__ == '__main__':46 if len(sys.argv) > 1:47 from jinja import FileSystemLoader48 e.loader = FileSystemLoader(sys.argv[1])49 if len(sys.argv) > 2:50 p(f=sys.argv[2])51 else:52 p(sys.stdin.read())
modified:TODO+21 added-4 removed
1===================2TODO List for Jinja3===================45- Improve the context lookup (maybe with an optional C extension)51.1:67 - Improve the context lookup (maybe with an optional C extension) [DONE]8 - make Undefined exchangeable [DONE]9 - implement block.super [DONE]10 - Implement a `IntrospectionPrinter` that works like pprint but it outputs11 either plain text or html. It would also have to cover changing names of12 the special builtins True, False etc to lowercase in order to not13 confuse people.14 - decide on `{% call %}`15 - speed up jinja import16 - add optional zlib compression of template bytecode17 - write more unittests!!!!18191.2:207- `include` and `extends` should work with dynamic data too. In order to8 support this the blocks should be stored as importable functions in the9 generated source.21 - `include` and `extends` should work with dynamic data too. In order to22 support this the blocks should be stored as importable functions in the23 generated source.24 - add support for `{% include myfile = 'myfile.html' %}` and give the25 template designer to access variables and macros defined in the template26 root or requirements namespace.