[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
Provenance
- Commit
fb5bebc- Tree
87d4322- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6c939e7
20 files changed+1154 added−517 removed
added:docs/src/api.txt+315 added
1+=======================2+Context and Environment3+=======================4+5+The two central objects in Jinja are the `Environment` and `Context`. Both6+are designed to be subclassed by applications if they need to extend Jinja.7+8+Environment9+===========10+11+The initialization parameters are already covered in the `Quickstart`_ thus12+not repeated here.13+14+But beside those configurable instance variables there are some functions used15+in the template evaluation code you may want to override:16+17+**def** `parse` *(source, filename)*:18+19+ 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.22+23+**def** `lex` *(source, filename)*:24+25+ 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**30+31+**def** `from_string` *(source)*:32+33+ 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.36+37+**def** `get_template` *(name)*:38+39+ Load a template from a loader. If the template does not exist, you will40+ get a `jinja.exceptions.TemplateNotFound` exception.41+42+**def** `to_unicode` *(self, value)*:43+44+ 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.47+48+ Also `None` is converted into an empty string per default.49+50+**def** `get_translator` *(self, context)*:51+52+ 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`_.57+58+ If you don't provide a translator a default one is used to switch59+ between singular and plural forms.60+61+ Have a look at the `i18n`_ section for more information.62+63+**def** `get_translations` *(self, name)*:64+65+ Get the translations for the template `name`. Only works if a loader66+ is present. See the `i18n`_ section for more details.67+68+**def** `get_translations_for_string` *(self, string)*:69+70+ 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.73+74+**def** `apply_filters` *(self, value, context, filters)*:75+76+ 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:81+82+ .. sourcecode:: python83+84+ [('escape', ()), ('replace', (u'a', u'b'))]85+86+ 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.90+91+ **Warning** this is a Jinja internal method. The actual implementation92+ and function signature might change.93+94+**def** `perform_test` *(self, context, testname, args, value, invert)*:95+96+ Like `apply_filters` you usually don't override this one. It's the97+ callback function for tests (``foo is bar`` / ``foo is not bar``).98+99+ 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.103+104+ Missing tests should raise a `TestNotFound` exception.105+106+ **Warning** this is a Jinja internal method. The actual implementation107+ and function signature might change.108+109+**def** `get_attribute` *(self, obj, attribute)*:110+111+ Get `attribute` from the object provided. The default implementation112+ performs security tests.113+114+ **Warning** this is a Jinja internal method. The actual implementation115+ and function signature might change.116+117+**def** `get_attributes` *(self, obj, attributes)*:118+119+ Get some attributes from the object. If `attributes` is an empty120+ sequence the object itself is returned unchanged.121+122+**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.128+129+ The default implementation performs some security checks.130+131+ **Warning** this is a Jinja internal method. The actual implementation132+ and function signature might change.133+134+**def** `call_function_simple` *(self, f, context)*:135+136+ Like `call_function` but without arguments.137+138+ **Warning** this is a Jinja internal method. The actual implementation139+ and function signature might change.140+141+**def** `finish_var` *(self, value, ctx)*:142+143+ Postprocess a variable before it's sent to the template.144+145+ **Warning** this is a Jinja internal method. The actual implementation146+ and function signature might change.147+ 148+.. admonition:: Note149+150+ The Enviornment class is defined in `jinja.environment.Environment`151+ but imported into the `jinja` package because it's often used.152+153+Context154+=======155+156+Jinja wraps the variables passed to the template in a special class called a157+context. This context supports variables on multiple layers and lazy (deferred)158+objects. Often your application has a request object, database connection159+object or something similar you want to access in filters, functions etc.160+161+The default context object is defined in `jinja.datastructure`. If you want162+to provide your own context object always subclass the default one. This163+ensures that the class continues working after Jinja upgrades.164+165+Beacause of that you can easily subclass a context to add additional variables166+or to change the way it behaves.167+168+**def** `pop` *(self)*:169+170+ Pop the outermost layer and return it.171+172+**def** `push` *(self, data=None)*:173+174+ Push a dict to the stack or an empty layer.175+176+ Has to return the pushed object.177+178+**def** `to_dict` *(self)*:179+180+ Flatten the context and convert it into a dict.181+182+**def** `__getitem__` *(self, name)*:183+184+ Resolve an item. Per default this also resolves `Deferred` objects.185+186+**def** `__setitem__` *(self, name, value)*:187+188+ Set an item in the outermost layer.189+190+**def** `__delitem__` *(self, name)*:191+192+ Delete an item in the outermost layer. Do not raise exceptions if193+ the value does not exist.194+195+**def** `__contains__` *(self, name)*:196+197+ Return `True` if `name` exists in the context.198+199+**attribute** `cache`:200+201+ 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.204+205+**attribute** `translate_func`:206+207+ 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.210+211+.. admonition:: Note212+213+ 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:216+217+ `globals`:218+ 219+ The reference to the global namespace of the environment.220+ It's the lowest namespace on the stack and thus immutable221+222+ `initial`:223+224+ 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.228+229+ `current`:230+231+ The reference to the current active namespace. When the232+ context is initialized this automatically points to an233+ empty namespace.234+235+ 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.239+240+ This is done in order to keep the namespace clean.241+242+ 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`.247+248+ Since you cannot reproduce completely the same semantics in python249+ and the C API there are some things you should keep in mind:250+251+ - 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.254+255+ - `globals`, `current` and `initial` are read only attributes that256+ map to layers on the stack which you can of course modify.257+258+259+Exceptions260+==========261+262+During parsing and evaluation Jinja raises a couple of Jinja specific263+exceptions. All of those exceptions are defined in the `jinja.exceptions`264+module and are subclasses of the `TemplateError` class defined there.265+266+Here a list of exceptions that could occur:267+268+`SecurityException`:269+270+ 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.273+274+ If however the environment is configured to not silently fail it275+ could happen that this exception reaches the application.276+277+`FilterNotFound`:278+279+ 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.282+283+`FilterArgumentError`:284+285+ 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.287+288+`TestNotFound`:289+290+ 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.293+294+`TestArgumentError`:295+296+ 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.298+299+`TemplateNotFound`:300+301+ Raised if a template does not exist. Subclass of `IOError` too.302+303+`TemplateSyntaxError`:304+305+ Subclass of `SyntaxError` and used to indicate an syntax error.306+307+`TemplateRuntimeError`:308+309+ Generic runtime error exception which can occour at various places.310+311+312+.. _i18n: i18n.txt313+.. _translators: translators.txt314+.. _Quickstart: devintro.txt315+.. _gettext documentation: http://docs.python.org/lib/module-gettext.htmlmodified:docs/src/designerdoc.txt+146 added-56 removed
233 unmodified lines234 is checked.235 236 *new in Jinja 1.1*237 238-`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)245-246- .. sourcecode:: jinja247-248- {% for items in seq %}249- {% for item in items %}250- <li>{{ item|e }}</li>251- {% endfor %}252- {{ flush() }}253- {% endfor %}254-255- *new in Jinja 1.1*256-238 Loops239 =====240 241 To iterate over a sequence, you can use the `for` loop. It basically looks like a242 unmodified lines484 {% endmacro %}485 486 {{ show_dialog('Warning', 'something went wrong i guess') }}487 488+*Improvements in Jinja 1.1*:489+490+ Starting with Jinja 1.1 it's possible to use optional parentheses491+ around the macro arguments:492+493+ .. sourcecode:: html+jinja494+495+ {% macro foo(a, b) %}496+ ...497+ {% endmacro %}498+499+ Additionally extra arguments passed to the macro end up in the500+ special variable `varargs`. So you can have a macro like this:501+502+ .. sourcecode:: html+jinja503+504+ {% 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 %}513+514+ {{ make_list("John", "Jane", "Marcus", "Heinrich") }}515+516+ If a macro parameter is called `varargs` the additional extra517+ arguments are not accessible.518+519+520 Inheritance521 ===========522 523 The most powerful part of Jinja is template inheritance. Template inheritance179 unmodified lines703 The variable ``angryname`` just exists inside the macro, not outside it.704 705 Defined macros appear on the context as variables. Because of this, they are706 affected by the scoping too. A macro defined inside of a macro is just available694-in those two macros (the macro itself and the macro it's defined in). For `set`695-and `macro` two additional rules exist: If a macro is defined in an extended696-template but outside of a visible block (thus outside of any block) will be697-available in all blocks below. This allows you to use `include` statements to698-load often used macros at once.707+in those two macros (the macro itself and the macro it's defined in).708 709+Template Globals710+================711+712+A special threatment exists for template code outside of visible blocks in713+child templates. This code will be executed **before** the layout template714+code. Thus it can be used to propagate values back to the layout template or715+import macros from templates for rendering.716+717+Such code can output data but it won't appear in the final rendering. So no718+additional whitespace will pollute the template.719+720+Because this code is executed before the actual layout template code it's721+possible that the layout code overrides some of those variables. Usually722+this is not a problem because of different variable names but it can be723+a problem if you plan to specify default values.724+725+In that case you have to test if the variable is not defined before setting726+it:727+728+.. sourcecode:: jinja729+730+ {% if not page_title %}731+ {% set page_title = 'Default Page Title' %}732+ {% endif %}733+734+You can of course also use the `|default` filter.735+736+.. admonition:: Explanation737+738+ This template stored as `a.html`:739+740+ .. sourcecode:: html+jinja741+742+ <title>{{ title|default('Untitled') }}</title>743+ <body>{% block body %}{% endblock %}744+745+ ...and this child template stored as `b.html`:746+747+ .. sourcecode:: html+jinja748+749+ {% extends 'a.html' %}750+ {% include 'macros.tmpl' %}751+ {% set title = 'My Page' %}752+ {% block body %}{{ wrap(42) }}{% endblock %}753+754+ ...and this code in `macros.tmpl`:755+756+ .. sourcecode:: html+jinja757+758+ {% macro wrap(text) %}759+ [{{ text }}]760+ {% endmacro %}761+762+ ..will translate to something with the same semantics as this (just763+ that the value is not stored in a variable):764+765+ .. sourcecode:: html+jinja766+767+ {% 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>777+778+.. admonition:: Note779+780+ 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.784+785+786 Undefined Variables787 ===================788 789 If you have already worked with python you probably know about the fact that790 undefined variables raise an exception. This is different in Jinja. There is a791 special value called `undefined` that represents values that do not exist.792 707-This special variable works complete different from any variables you maybe708-know. If you print it using ``{{ variable }}`` it will not appear because it's709-literally empty. If you try to iterate over it, it will work. But no items710-are returned. Comparing this value to any other value results in `false`.711-Even if you compare it to itself:793+Depending on the configuration it will behave different.794 795+In order to check if a value is defined you can use the `defined` test:796+797 .. sourcecode:: jinja798 715- {{ 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.801 719- {{ undefined is not defined }}720- will return true.802+`SilentUndefined`:803 722-There are also some additional rules regarding this special value. Any723-mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand724-as 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.808 726-.. sourcecode:: jinja809+ In order to check if a value is defined you can use the `defined` test:810 728- {{ undefined + "foo" }}729- returns "foo"811+ There are also some additional rules regarding this special value. Any812+ mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand813+ as result:814 731- {{ undefined - 42 }}732- returns 42. Note: not -42!815+ .. sourcecode:: jinja816 734-In any expression `undefined` evaluates to `false`. It has no length, all735-attribute calls return undefined, calling too:817+ {{ undefined + "foo" }}818+ returns "foo"819 737-.. sourcecode:: jinja820+ {{ undefined - 42 }}821+ returns 42. Note: not -42!822 739- {{ 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:825 742-Starting with Jinja 1.1 it's possible to control the `undefined` behavior743-in the Jinja environment, thus on the application side. If you receive744-a `TemplateRuntimeError` when operating on an undefined variable the745-environment was created with `silent` disabled.826+ .. sourcecode:: jinja827 747-In a non silent environment the error you get tells you the line number748-and the name of the variable / attribute which could not be found.828+ {{ undefined.attribute().attribute_too[42] }}829+ still returns `undefined`.830 831+`ComplainingUndefined`:832+833+ 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.836+837+ It raises exceptions as soon as you either render it or want to iterate838+ over it or try to access attributes etc.839+ 840+841 Escaping842 ========843 844 Sometimes you might want to add Jinja syntax elements into the template202 unmodified lines1047 </div>1048 </div>1049 {% endmacro %}1050 960- 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:1053 1054 .. sourcecode:: html+jinja1055 1056 {% call dialog('Hello World') %}35 unmodified linesmodified:docs/src/devintro.txt+16 added
72 unmodified lines73 74 There are also some internal functions on the environment used by the template75 evaluation code to keep it sandboxed.76 77+Undefined Values78+================79+80+If a template designer tries to access a not defined value the return value81+will be the `undefined_singleton` specified in the environment. The default82+one is the `SilentUndefined` which fails in no case. Additionally there is83+a special undefined type called the `ComplainingUndefined` which is located84+in the `jinja.datastructure` module. It will raise exceptions when compared85+with other types, or when rendered.86+87+Theoretically 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 cover90+the basic use cases. The `Undefined` object in that module exists for91+backwards compatibility and is an alias for `SilentUndefined`.92+93 Automatic Escaping94 ==================95 96 Jinja provides a way for automatic escaping, but we do not recommend using it.65 unmodified linesmodified:docs/src/streaming.txt+46 added-72 removed
8 unmodified lines9 If you for example generate a file with a couple of megabytes you may want10 to pass the stream to the WSGI interface in order to keep the amount of11 memory used low and deliver the output to the browser as fast as possible.12 13-The streaming works quite simple. Whenever an item is returned by the14-internal generator it's passed to a `TemplateStream` which buffers 40 events15-before yielding them. Because WSGI usually slows down on too many flushings16-this is the integrated solution for this problem. The template designer17-can further control that behavior by placing a ``{{ flush() }}`` call in18-the template. Whenever the `TemplateStream` encounters an object marked as19-flushable it stops buffering and yields the item.13+The streaming interface is straightforward. Instead of using `render()` you14+can call `stream()` which does pretty much the same but doesn't return a15+string but a `TemplateStream`:16 21-Note that some constructs are not part of the stream. For example blocks22-that are rendered using ``{{ super() }}`` are yielded as one flushable item.17+.. sourcecode:: pycon18 24-This restriction exists because template designers may want to operate on25-the 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>'34 27-The following constructs yield their subcontents as one event: ``blocks``28-that are not the current one (eg, blocks called using ``{{ super() }}``),29-macros, filtered sections.35+As you can see each iteration is threated as template event here. But also36+other tags trigger events. Basically every tag yields one event, the37+`print` tag too. The only exception is the variable substitution syntax which38+is inserted into the template text data.39 31-The TemplateStream32-==================40+Because some protocols like `WSGI` flush after each iteration if passed as41+response iterable it's better to buffer some events internally. You can do42+this by enable buffering using `enable_buffering` and passing it the buffer43+size which must be greater than one:44 34-You can get a new `TemplateStream` by calling the `stream()` function on35-a template like you would do for rendering. The `TemplateStream` behaves36-like a normal generator/iterator. However, as long as the stream is not37-started you can modify the buffer threshold. Once the stream started38-streaming it looses the `threshold` attribute.39-40-Explicit flushing:41-45 .. sourcecode:: pycon46 44- >>> 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>'52 57-Implicit flushing after 6 events:53+This will buffer 3 events before yielding. Disabling buffering works using the54+`disable_buffering` method. You can enable and disable buffering on the fly also55+if you have already iterated over that stream. To check if you are in buffered56+or unbuffered mode you can use the `.buffered` property:57 58 .. sourcecode:: pycon59 61- >>> 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>'73-74-General `TemplateStream` behavior:75-76-.. sourcecode:: pycon77-78- >>> 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+ False68 69+.. admonition:: Note70 93-Stream Control94-==============71+ Jinja uses buffering internally for some constructs like macros. A macro72+ call is yielded as one event, independently of the internal structure.73 96-The stream control is designed so that it's completely transparent. When used97-in non stream mode the invisible flush tokens disappear. In order to flush98-the stream after calling a specific function all you have to do is to wrap99-the return value in a `jinja.datastructure.Flush` object. This however100-bypasses 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 lines15 16 It also adds debug symbols used by the traceback toolkit implemented17 in `jinja.utils`.18 19+ Implementation Details20+ ======================21+22+ 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.27+28+ 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.33+34 :copyright: 2007 by Armin Ronacher.35 :license: BSD, see LICENSE for more details.36 """37 import re12 unmodified lines50 #: regular expression for the debug symbols51 _debug_re = re.compile(r'^\s*\# DEBUG\(filename=(?P<filename>.*?), '52 r'lineno=(?P<lineno>\d+)\)$')53 54+# For Python2.3 compatibiilty55+try:56+ set57+except NameError:58+ from sets import Set as set59 60+# For Python 2.3/2.4 compatibility61 try:62 GeneratorExit63 except NameError:64 class GeneratorExit(Exception):44- """For python2.3/python2.4 compatibility"""65+ pass66 46-67+# For Pythons without conditional expressions68 try:48- set49-except NameError:50- from sets import Set as set69+ exec '0 if 0 else 0'70+ have_conditional_expr = True71+except SyntaxError:72+ have_conditional_expr = False73 74 53-def _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- )61-62-75 class Template(object):76 """77 Represents a finished template.78 """93 unmodified lines172 self.constants = {173 'true': 'True',174 'false': 'False',175 'none': 'None',164- 'undefined': 'Undefined'176+ 'undefined': 'undefined_singleton'177 }178 179 #: bind the nodes to the callback functions. There are180 #: some missing! A few are specified in the `unhandled`3 unmodified lines184 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 lines266 first line.267 """268 return (' ' * (self.indention * 4)) + text269 270+ 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+ )278+279 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 lines313 '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))328 329 def handle_node(self, node):330 """331 Handle one node. Resolves the correct callback functions defined13 unmodified lines345 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 = False362 363 def translate(self):364 """365 Translate the node defined in the constructor after16 unmodified lines382 # 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>'391 392+ # 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()396+397 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)]406 407 # load the template we inherit from and add not known blocks408 parent = self.environment.loader.parse(node.extends.template,409 node.filename)5 unmodified lines415 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 = parent425 382- # 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)388-389- # 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']]393-394- # 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- ]413-414- # 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')437 420- # 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]440 423- # add body lines and "generator hook"424- lines.extend(body_lines)425- lines.append(' if 0: yield None')426-427- # 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 line448 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 ))474 475+ # 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]480+481+ # 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+ ])508+509+ # 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')514+515+ # now write the bootstrapping (requirements) core if there is one516+ if requirements:517+ lines.append('# Bootstrapping code')518+ lines.extend(requirement_lines)519+520 # 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')530 531 # now get the real source lines and map the debugging symbols532 debug_mapping = []533 file_mapping = {}6 unmodified lines540 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 lines559 else:560 result.append(line)561 562 # 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)570 571 def handle_template_text(self, node):572 """7 unmodified lines580 data = node.text581 return self.indent(self.nodeinfo(node)) + '\n' +\582 self.indent('yield %r' % data)583 584+ 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')592+593+ 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(')')601+602+ return '\n'.join(buf)603+604 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 lines617 """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()')626 627 # 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 lines662 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 lines700 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 lines712 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 -= 1723 724+ 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 lines737 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 lines766 767 # collect macro arguments768 arg_items = []769 caller_overridden = False770+771+ # 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]'781+782 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'798+799 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)805 806+ write('ctx_push({%s})' % ',\n '.join([807+ idx and self.indent(item) or item for idx, item808+ in enumerate(arg_items)809+ ]))810+811 # 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 -= 1818 819 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')829 830 return '\n'.join(buf)831 832 def handle_call(self, node):5 unmodified lines838 839 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')851 852 return '\n'.join(buf)853 854 def handle_set(self, node):18 unmodified lines873 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)887 888 def handle_block(self, node, level=0):889 """4 unmodified lines894 rv = self.handle_node(node.body)895 if not rv:896 return ''897 898+ self.used_data_structures.add('SuperBlock')899 buf = []900 write = lambda x: buf.append(self.indent(x))901 902 write(self.nodeinfo(node))1 unmodified line904 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)911 912 def handle_include(self, node):87 unmodified lines1000 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 lines1039 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 line1049 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 line1059 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])1064 1065 def handle_bitor(self, node):1066 """1067 We use the pipe operator for filtering.16 unmodified lines1084 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 linesmodified:jinja/_native.py+3 added-6 removed
12 unmodified lines13 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15 """16 from jinja.datastructure import Deferred, Undefined17-from jinja.exceptions import TemplateRuntimeError17 18 19 class BaseContext(object):20 22- 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.pop36 unmodified lines63 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_singleton68 69 def __setitem__(self, name, value):70 """71 Set a variable in the outermost layer.24 unmodified linesmodified:jinja/_speedups.c+38 added-127 removed
16 unmodified lines17 #include <Python.h>18 #include <structmember.h>19 20 /* Set by init_constants to real values */21-static PyObject *Undefined, *Deferred, *TemplateRuntimeError;22-static Py_UNICODE *amp, *lt, *gt, *qt;21+static PyObject *Deferred;22 23 /**24 * Internal struct used by BaseContext to store the25 * stacked namespaces.11 unmodified lines37 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;43 44 /**45 * Called by init_speedups in order to retrieve references4 unmodified lines50 {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");63-64- amp = ((PyUnicodeObject*)PyUnicode_DecodeASCII("&", 5, NULL))->str;65- lt = ((PyUnicodeObject*)PyUnicode_DecodeASCII("<", 4, NULL))->str;66- gt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(">", 4, NULL))->str;67- qt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(""", 6, NULL))->str;68-55 Py_DECREF(datastructure);70- Py_DECREF(exceptions);56 return 1;57 }58 59 /**75- * SGML/XML escape something.76- *77- * XXX: this is awefully slow for non unicode objects because they78- * get converted to unicode first.79- */80-static PyObject*81-escape(PyObject *self, PyObject *args)82-{83- PyUnicodeObject *in, *out;84- Py_UNICODE *outp;85- int i, len;86-87- PyObject *text = NULL, *use_quotes = NULL;88-89- 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;95-96- /* 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- }114-115- /* Do we need to escape anything at all? */116- if (len == in->length)117- return (PyObject*)in;118-119- out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, len);120- if (!out) {121- Py_DECREF(in);122- return NULL;123- }124-125- 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- }152-153- Py_DECREF(in);154- return (PyObject*)out;155-}156-157-/**60 * Deallocator for BaseContext.61 *62 * Frees the memory for the stack layers before freeing the object.63 */13 unmodified lines77 78 /**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 */87 static int88 BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)89 {188- PyObject *silent = NULL, *globals = NULL, *initial = NULL;90+ PyObject *undefined = NULL, *globals = NULL, *initial = NULL;91 190- 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 }98 199- self->silent = PyObject_IsTrue(silent);200- if (self->silent == -1)201- return -1;202-99 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 lines113 self->globals->dict = globals;114 Py_INCREF(globals);115 self->initial->prev = self->globals;116 117+ self->undefined_singleton = undefined;118+ Py_INCREF(undefined);119+120 self->stacksize = 3;121 return 0;122 }123 121 unmodified lines245 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;257 258 /* disallow access to internal jinja values */259 name = PyString_AS_STRING(item);31 unmodified lines291 return result;292 }293 294 missing: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 }298 299 /**300 * Check if the context contains a given value.3 unmodified lines304 {305 char *name;306 struct StackLayer *current = self->current;307 308+ /* 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;316 317 name = PyString_AS_STRING(item);318 if (name[0] && name[0] == ':' && name[1] == ':')16 unmodified lines335 */336 static int337 BaseContext_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);352+353+error:354+ PyErr_SetString(PyExc_TypeError, "expected string argument");355+ return -1;356 }357 358 /**359 * Size of the stack.89 unmodified lines449 PyType_GenericNew /* tp_new */450 };451 452 static 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 };455 456 #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */20 unmodified linesmodified:jinja/datastructure.py+120 added-69 removed
32 unmodified lines33 f.jinja_unsafe_call = True34 return f35 36 37-class UndefinedType(object):37+def 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 self46+47+48+class AbstractUndefinedType(object):49+ """50+ Base class for any undefined type.51+ """52 __slots__ = ()53 54 def __init__(self):55 raise TypeError('cannot create %r instances' %56 self.__class__.__name__)57 58+ def __setattr__(self, name, value):59+ raise AttributeError('%r object has no attribute %r' % (60+ self.__class__.__name__,61+ name62+ ))63+64+ def __eq__(self, other):65+ return self is other66+67+ def __ne__(self, other):68+ return self is not other69+70+ def __copy__(self):71+ return self72+ __deepcopy__ = __copy__73+74+ def __reduce__(self):75+ raise TypeError('undefined objects have to provide a __reduce__')76+77+78+class SilentUndefinedType(AbstractUndefinedType):79+ """80+ An object that does not exist.81+ """82+ __slots__ = ()83+84 def __add__(self, other):85 """Any operator returns the operand."""86 return other87 __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __mod__ =\27 unmodified lines115 def __unicode__(self):116 """The unicode representation is empty."""117 return u''118 82- def __repr__(self):83- """The representation is ``'Undefined'``"""84- return 'Undefined'85-119 def __int__(self):120 """Converting `Undefined` to an integer ends up in ``0``"""121 return 0122 123 def __float__(self):124 """Converting `Undefined` to an float ends up in ``0.0``"""125 return 0.0126 94- def __eq__(self, other):95- """`Undefined` is not equal to anything else."""96- return False97-98- def __ne__(self, other):99- """`Undefined` is not equal to anything else."""100- return True101-127 def __call__(self, *args, **kwargs):128 """Calling `Undefined` returns `Undefined`"""129 return self130 106- def __copy__(self):107- """Return a copy."""108- return self131+ def __reduce__(self):132+ """Helper for pickle."""133+ return 'SilentUndefined'134 110- def __deepcopy__(self, memo):111- """Return a deepcopy."""112- return self135 136+class ComplainingUndefinedType(AbstractUndefinedType):137+ """138+ An object that does not exist.139+ """140+ __slots__ = ()141+142+ def __iter__(self):143+ """Iterating over `Undefined` returns an empty iterator."""144+ if False:145+ yield None146+147+ def __nonzero__(self):148+ """`Undefined` is considered boolean `False`"""149+ return False150+151+ def __str__(self):152+ """The string representation raises an error."""153+ raise TemplateRuntimeError('Undefined object rendered')154+155+ def __unicode__(self):156+ """The unicode representation raises an error."""157+ self.__str__()158+159+ def __call__(self, *args, **kwargs):160+ """Calling `Undefined` returns `Undefined`"""161+ raise TemplateRuntimeError('Undefined object called')162+163 def __reduce__(self):164 """Helper for pickle."""116- return 'Undefined'165+ return 'ComplainingUndefined'166 167 119-#: the singleton instance of UndefinedType120-Undefined = object.__new__(UndefinedType)168+#: the singleton instances for the undefined objects169+SilentUndefined = make_undefined(SilentUndefinedType)170+ComplainingUndefined = make_undefined(ComplainingUndefinedType)171 172+#: jinja 1.0 compatibility173+Undefined = SilentUndefined174+UndefinedType = SilentUndefinedType175 176+177 class FakeTranslator(object):178 """179 Default null translator.180 """44 unmodified lines225 template. The autoescape filter can use that.226 """227 228 175-class Flush(TemplateData):176- """177- After a string marked as Flush the stream will stop buffering.178- """179-180- jinja_no_finalization = True181-182-229 # import these here because those modules import Deferred and Undefined230 # from this module.231 try:232 # try to use the c implementation of the base context if available9 unmodified lines242 """243 244 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 lines525 526 527 class 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.486-487- 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 """531 532 def __init__(self, gen):493- self._next = gen.next494- self._threshold = None495- self.threshold = 40533+ self._gen = gen534+ self._next = gen._next535+ self.buffered = False536 537+ def disable_buffering(self):538+ """539+ Disable the output buffering.540+ """541+ self._next = self._gen.next542+ self.buffered = False543+544+ 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 = True552+553+ def buffering_next():554+ buf = []555+ c_size = 0556+ push = buf.append557+ next = self._gen.next558+559+ 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)571+572+ self._next = buffering_next573+574 def __iter__(self):575 return self576 500- def started(self):501- return self._threshold is not None502- started = property(started)503-577 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._next514-515- 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 lines10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13 from jinja.utils import debug_helper, safe_range, generate_lorem_ipsum, \14- watch_changes, flush14+ watch_changes15 16 17 __all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']18 1 unmodified line20 DEFAULT_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 lines11 import re12 from jinja.lexer import Lexer13 from jinja.parser import Parser14 from jinja.loaders import LoaderWrapper15-from jinja.datastructure import Undefined, Markup, Context, FakeTranslator15+from jinja.datastructure import SilentUndefined, Markup, Context, FakeTranslator16 from jinja.utils import collect_translations, get_attribute17 from jinja.exceptions import FilterNotFound, TestNotFound, \18 SecurityException, TemplateSyntaxError, TemplateRuntimeError19 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE27 unmodified lines47 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 lines96 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 traceback23 unmodified lines129 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_traceback135 136 # global namespace137 if namespace is None:72 unmodified lines210 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')226 227 def get_translator(self, context):228 """229 Return the translator for i18n.61 unmodified lines291 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_singleton298 299 def get_attributes(self, obj, attributes):300 """301 Get some attributes from an object. If attributes is an14 unmodified lines316 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 lines328 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 lines339 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 linesmodified:jinja/filters.py+9 added-14 removed
10 unmodified lines11 import re12 from random import choice13 from urllib import urlencode, quote14 from jinja.utils import urlize, escape15-from jinja.datastructure import Undefined, Markup, TemplateData15+from jinja.datastructure import Markup, TemplateData16 from jinja.exceptions import FilterArgumentError17 18 19 try:93 unmodified lines113 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 wrapped27 unmodified lines150 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 lines236 237 {{ ''|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 lines314 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 wrapped320 321 322 def do_last():3 unmodified lines326 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 wrapped332 333 334 def do_random():3 unmodified lines338 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 wrapped344 345 346 def do_urlencode():302 unmodified lines649 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 wrapped656 657 196 unmodified linesmodified:jinja/nodes.py+22 added
71 unmodified lines72 def __repr__(self):73 return 'Text(%r)' % (self.text,)74 75 76+class 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+ """82+83+ def __init__(self, lineno, format_string, variables):84+ self.lineno = lineno85+ self.format_string = format_string86+ self.variables = variables87+88+ def get_items(self):89+ return [self.format_string] + list(self.variables)90+91+ def __repr__(self):92+ return 'DynamicText(%r, %r)' % (93+ self.text,94+ self.variables95+ )96+97+98 class NodeList(list, Node):99 """100 A node that stores multiple childnodes.101 """296 unmodified linesmodified:jinja/parser.py+49 added-7 removed
85 unmodified lines86 }87 88 #: 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 ])94 95 self.tokenstream = environment.lexer.tokenize(source, filename)96 125 unmodified lines222 return nodes.Print(lineno, arguments[0])223 224 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 lines240 raise TemplateSyntaxError('illegal use of keyword %r '241 'as macro name.' % macro_name[2],242 lineno, self.filename)243 244+ # 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]249+243- 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 lines626 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 result635 636+ 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[:]662+663 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 line671 # 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)))676 677 # 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()684+685 gen = self.tokenstream.fetch_until(end_of_block, True)686 try:687 lineno, token, data = gen.next()688 except StopIteration:38 unmodified lines727 # 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))732 733 # so this should be unreachable code734 else:735 raise AssertionError('unexpected token %r (%r)' % (token,32 unmodified linesmodified:jinja/tests.py+1 added-2 removed
7 unmodified lines8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12-from jinja.datastructure import Undefined12 13 14 number_re = re.compile(r'^-?\d+(\.\d+)?$')15 27 unmodified lines43 {% endif %}44 45 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_singleton48 49 50 def test_lower():51 """73 unmodified linesmodified:jinja/utils.py+42 added-31 removed
15 unmodified lines16 import string17 from types import MethodType, FunctionType18 from compiler.ast import CallFunc, Name, Const19 from jinja.nodes import Trans20-from jinja.datastructure import Context, Flush20+from jinja.datastructure import Context21 from jinja.exceptions import SecurityException, TemplateNotFound22 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 higher26-if 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 higher26+try:27 from collections import deque28-else:28+ deque.remove29+except (ImportError, AttributeError):30 deque = None31 32+# support for python 2.3/2.433 try:34 set35 except NameError:36 from sets import Set as set14 unmodified lines51 52 #: used by from_string as cache53 _from_string_env = None54 55+56+def escape(s, quote=None):57+ """58+ SGML/XML escape an unicode object.59+ """60+ s = s.replace("&", "&").replace("<", "<").replace(">", ">")61+ if not quote:62+ return s63+ return s.replace('"', """)64+65+66 def 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 lines204 return u'\n\n'.join(result)205 return u'\n'.join([u'<p>%s</p>' % escape(x) for x in result])206 207 195-def flush():196- """197- Yield a flush marker.198- """199- return Flush()200-201-208 def watch_changes(env, context, iterable, *attributes):209 """210 Wise replacement for ``{% ifchanged %}``.211 """31 unmodified lines243 244 # 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.247+try:248+ _test_singleton = object()249+ def _test_gen_bug():250+ raise TypeError(_test_singleton)251+ yield None252+ ''.join(_test_gen_bug())253+except TypeError, e:254+ if e.args and e.args[0] is _test_singleton:255+ capture_generator = u''.join256+ RUNTIME_EXCEPTION_OFFSET = 1241-if 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 = 2260+del _test_singleton, _test_gen_bug261 245-# this should be faster and used in python2.5 and higher246-else:247- capture_generator = u''.join248- RUNTIME_EXCEPTION_OFFSET = 1262 250-263 def 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 wrapped271 272 273+def 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 None279+280+281 def fake_template_exception(exception, filename, lineno, source,282 context_or_env):283 """284 Raise an exception "in a template". Return a traceback376 unmodified lines661 rv = CacheDict(self.capacity)662 rv._mapping = deepcopy(self._mapping)663 rv._queue = deepcopy(self._queue)664 return rv645-646-647-# escaping function. Use this only if you escape unicode648-# objects. in all other cases it's likely that the cgi.escape649-# function performs better.650-try:651- from jinja._speedups import escape652-except ImportError:653- from cgi import escapemodified:tests/runtime/bigtable.py+1 added-1 removed
39 unmodified lines40 have_mako = True41 except ImportError:42 have_mako = False43 44-table = [dict(a='1',b='2',c='3',d='4',e='5',f='6',g='7',h='8',i='9',j='10')44+table = [dict(zip('abcdefghij', map(unicode,range(1, 11))))45 for x in range(1000)]46 47 genshi_tmpl = MarkupTemplate("""48 <table xmlns:py="http://genshi.edgewall.org/">124 unmodified linesadded:tests/runtime/modglobals.py+37 added
1+# test file for block super support2+import jdebug3+from jinja import Environment, DictLoader4+5+env = 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 }}24+25+ 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+}))35+36+tmpl = env.get_template('c')37+print tmpl.render()modified:CHANGES+11 added-2 removed
33 unmodified lines34 - it's now possible to use newlines in string literals35 36 - developer friendly traceback is now toggleable37 38-- silent variable name failure is now toggleable38+- the variable failure is now pluggable by replacing the undefined39+ singleton for an environment instance40 41 - fixed issue with old-style classes not implementing `__getitem__`42 (thanks to Axel Böhm for discovering that bug)43 24 unmodified lines68 69 - You can now use the environment to just tokenize a template. This can70 be useful for syntax highlighting or other purposes.71 71-- added optional c-implementation of the context baseclass.72+- added optional C-implementation of the context baseclass.73 74+- 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 %}``.77+78+- additional macro arguments now end up in `varargs`.79+80 - implemented `{% call %}` - unsure if this makes it into the final release.81 82+- it's not possible to stream templates.83 84+85 Version 1.086 -----------87 (released Mar 23, 2007)88 1 unmodified linemodified:jdebug.py+12 added-1 removed
31 unmodified lines32 33 PythonTranslator.translate = debug_translate34 35 36-def p(x, f=None):36+def 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()40 41 def l(x):42 for item in e.lexer.tokenize(x):43 print '%5s %-20s %r' % item44+45+if __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 ===================2 TODO List for Jinja3 ===================4 5-- Improve the context lookup (maybe with an optional C extension)5+1.1:6 7+ - 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!!!!18+19+1.2:20+7-- `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.