[svn] added c implementation of the jinja context class.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 6d0b195 · Browse files · 22 files·+791 added−321 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
22 files+791 added−321 removed
- tests:+13 added−2 removed
- other:+778 added−319 removed
Provenance
- Commit
ee2c18e- Tree
f3e2152- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6d0b195
22 files changed+791 added−321 removed
deleted:docs/src/contextenv.txt-173 removed
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** `to_unicode` *(self, value)*:18-19- Called to convert variables to unicode. Per default this checks if the20- value is already unicode. If not it's converted to unicode using the21- charset defined on the environment.22-23- Also `None` is converted into an empty string per default.24-25-**def** `get_translator` *(self, context)*:26-27- Return the translator used for i18n. A translator is an object that28- provides the two functions ``gettext(string)`` and29- ``ngettext(singular, plural, n)``. Both of those functions have to30- behave like the `ugettext` and `nugettext` functions described in the31- python `gettext documentation`_.32-33- If you don't provide a translator a default one is used to switch34- between singular and plural forms.35-36- Have a look at the `i18n`_ section for more information.37-38-**def** `get_translations` *(self, name)*:39-40- Get the translations for the template `name`. Only works if a loader41- is present. See the `i18n`_ section for more details.42-43-**def** `get_translations_for_string` *(self, string)*:44-45- Get the translations for the string `string`. This works also if no46- loader is present and can be used to lookup translation strings from47- templates that are loaded from dynamic resources like databases.48-49-**def** `apply_filters` *(self, value, context, filters)*:50-51- Now this function is a bit tricky and you usually don't have to override52- it. It's used to apply filters on a value. The Jinja expression53- ``{{ foo|escape|replace('a', 'b') }}`` calls the function with the54- value of `foo` as first parameter, the current context as second and55- a list of filters as third. The list looks like this:56-57- .. sourcecode:: python58-59- [('escape', ()), ('replace', (u'a', u'b'))]60-61- As you can see the filter `escape` is called without arguments whereas62- `replace` is called with the two literal strings ``a`` and ``b``, both63- unicode. The filters for the names are stored on ``self.filters`` in a64- dict. Missing filters should raise a `FilterNotFound` exception.65-66- **Warning** this is a Jinja internal method. The actual implementation67- and function signature might change.68-69-**def** `perform_test` *(self, context, testname, args, value, invert)*:70-71- Like `apply_filters` you usually don't override this one. It's the72- callback function for tests (``foo is bar`` / ``foo is not bar``).73-74- The first parameter is the current contex, the second the name of75- the test to perform. the third a tuple of arguments, the fourth is76- the value to test. The last one is `True` if the test was performed77- with the `is not` operator, `False` if with the `is` operator.78-79- Missing tests should raise a `TestNotFound` exception.80-81- **Warning** this is a Jinja internal method. The actual implementation82- and function signature might change.83-84-**def** `get_attribute` *(self, obj, attribute)*:85-86- Get `attribute` from the object provided. The default implementation87- performs security tests.88-89- **Warning** this is a Jinja internal method. The actual implementation90- and function signature might change.91-92-**def** `get_attributes` *(self, obj, attributes)*:93-94- Get some attributes from the object. If `attributes` is an empty95- sequence the object itself is returned unchanged.96-97-**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:98- 99- Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and100- `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`101- is not `None` you have to add it to the arguments, if `dyn_kwargs` is102- not `None` you have to update the `kwargs` with it.103-104- The default implementation performs some security checks.105-106- **Warning** this is a Jinja internal method. The actual implementation107- and function signature might change.108-109-**def** `call_function_simple` *(self, f, context)*:110-111- Like `call_function` but without arguments.112-113- **Warning** this is a Jinja internal method. The actual implementation114- and function signature might change.115-116-**def** `finish_var` *(self, value, ctx)*:117-118- Postprocess a variable before it's sent to the template.119-120- **Warning** this is a Jinja internal method. The actual implementation121- and function signature might change.122- 123-.. admonition:: Note124-125- The Enviornment class is defined in `jinja.environment.Environment`126- but imported into the `jinja` package because it's often used.127-128-Context129-=======130-131-Jinja wraps the variables passed to the template in a special class called a132-context. This context supports variables on multiple layers and lazy (deferred)133-objects. Often your application has a request object, database connection134-object or something similar you want to access in filters, functions etc.135-136-Beacause of that you can easily subclass a context to add additional variables137-or to change the way it behaves.138-139-**def** `pop` *(self)*:140-141- Pop the outermost layer and return it.142-143-**def** `push` *(self, data=None)*:144-145- Push a dict to the stack or an empty layer.146-147- Has to return the pushed object.148-149-**def** `to_dict` *(self)*:150-151- Flatten the context and convert it into a dict.152-153-**def** `__getitem__` *(self, name)*:154-155- Resolve an item. Per default this also resolves `Deferred` objects.156-157-**def** `__setitem__` *(self, name, value)*:158-159- Set an item in the outermost layer.160-161-**def** `__delitem__` *(self, name)*:162-163- Delete an item in the outermost layer. Do not raise exceptions if164- the value does not exist.165-166-**def** `__contains__` *(self, name)*:167-168- Return `True` if `name` exists in the context.169-170-171-.. _i18n: i18n.txt172-.. _Quickstart: devintro.txt173-.. _gettext documentation: http://docs.python.org/lib/module-gettext.htmlmodified:docs/src/designerdoc.txt+1 added-1 removed
782 unmodified lines783 784 `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,785 `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,786 `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,787- `raw`, `recursive`, `set`, `trans`787+ `print`, `raw`, `recursive`, `set`, `trans`788 789 If you want to use such a name you have to prefix or suffix it or use790 alternative names:791 149 unmodified linesmodified:docs/src/devintro.txt+5 added
55 unmodified lines56 ``parse(source, filename)`` Parse the sourcecode and return the abstract57 syntax tree. This tree of nodes is used by the58 `translators`_ to convert the template into59 executable source- or bytecode.60+``lex(source, filename)`` Tokenize the given sourcecode and return a61+ generator of tuples in the form62+ ``(lineno, token, value)``. The filename is just63+ used in the exceptions raised.64+ **New in Jinja 1.1**65 ``from_string(source)`` Load and parse a template source and translate it66 into eval-able Python code. This code is wrapped67 within a `Template` class that allows you to68 render it.77 unmodified linesmodified:docs/src/index.txt+31 added-18 removed
4 unmodified lines5 Welcome in the Jinja documentation.6 7 - `Installing Jinja <installation.txt>`_8 9-- Application Developer Documentation:9+- **Application Developer Documentation**:10 11- - `Quickstart <devintro.txt>`_11+ - `Quickstart <devintro.txt>`_ - getting started with Jinja12 13- - `Template Loaders <loaders.txt>`_13+ - `Template Loaders <loaders.txt>`_ - documentation for the different14+ loader types and how to write custom ones.15 15- - `Filter Functions <filters.txt>`_16+ - `Filter Functions <filters.txt>`_ - information about how to write17+ custom filter functions.18 17- - `Test Functions <tests.txt>`_19+ - `Test Functions <tests.txt>`_ - information about how to write20+ custom test functions.21 19- - `Global Objects <objects.txt>`_22+ - `Global Objects <objects.txt>`_ - information about the special global23+ namespace in Jinja templates.24 21- - `Streaming Interface <streaming.txt>`_25+ - `Streaming Interface <streaming.txt>`_ - using Jinja for big templates26+ by streaming the output.27 23- - `Context and Environment <contextenv.txt>`_28+ - `Internationalization <i18n.txt>`_ - how to internationalize applications29+ using Jinja templates.30 25- - `Translators <translators.txt>`_31+ - `Alternative Syntax <altsyntax.txt>`_ - changing the default Jinja32+ block / variable / comment delimiters.33 27- - `Framework Integration <frameworks.txt>`_34+ - `API Documentation <api.txt>`_ - API documentation for public Jinja35+ objects like `Environment`.36 29- - `Debugging Support <debugging.txt>`_37+ - `Translators <translators.txt>`_ - explanation about the Jinja template38+ translation interface.39 31- - `Internationalization <i18n.txt>`_40+ - `Framework Integration <frameworks.txt>`_ - integrating Jinja into41+ python frameworks.42 33- - `Alternative Syntax <altsyntax.txt>`_43+ - `Debugging Support <debugging.txt>`_ - debugging Jinja templates.44 35- - `Developer Recipies <devrecipies.txt>`_45+ - `Developer Recipies <devrecipies.txt>`_ - tips and tricks for application46+ developers.47 37-- Template Designer Documentation:48+- **Template Designer Documentation**:49 39- - `Syntax Reference <designerdoc.txt>`_50+ - `Syntax Reference <designerdoc.txt>`_ - the designer documentation. Put51+ this under your pillow.52 41- - `Differences To Django <fromdjango.txt>`_53+ - `Differences To Django <fromdjango.txt>`_ - coming from django? Then this54+ document is for you.55 43- - `Designer Recipies <recipies.txt>`_56+ - `Designer Recipies <recipies.txt>`_ - various tips and tricks for designers.57 58 - `Changelog <changelog.txt>`_59 60 There is also support via IRC on the ``#pocoo`` channel on `irc.freenode.net`.modified:docs/src/objects.txt+2 added
72 unmodified lines73 The function is always called with the same arguments. The first one is the74 current environment, the second the context and the third is the name of the75 variable. In this example ``recent_comments``.76 77+The value is cached until rendering/streaming finished.78+79 Unsafe Methods / Attributes80 ===========================81 82 Because Jinja is sandboxed it provides several ways to prevent unsafe attribute48 unmodified linesmodified:docs/src/recipies.txt+13 added
167 unmodified lines168 <body>169 <div class="head">{{ title }}</div>170 </body>171 </html>172+173+174+Vim Syntax Highlighting175+=======================176+177+Because of the similar syntax to django you can use the django highlighting178+plugin for jinja too. There is however a Jinja syntax highlighting plugin179+too which supports all of the syntax elements.180+181+You can download it from the vim webpage: `jinja.vim`_182+183+184+.. _jinja.vim: http://www.vim.org/scripts/script.php?script_id=1856modified:docs/src/translators.txt+3 added-3 removed
3 unmodified lines4 5 Jinja translates the template sourcecode into executable python code behind6 the secenes. This is done by the python translator which is currently the7 only shipped translator. Because the interface isn't stable it's also not8-recommended yet to write other translators. However for the next Jinja version9-a JavaScript translator is planned which allows you to translate Jinja10-templates into executable JavaScript code.8+recommended yet to write other translators. However for one of the next Jinja9+versions a JavaScript translator is planned which allows you to translate10+Jinja templates into executable JavaScript code.modified:jinja/translators/python.py+86 added-27 removed
42 unmodified lines43 class GeneratorExit(Exception):44 """For python2.3/python2.4 compatibility"""45 46 47+try:48+ set49+except NameError:50+ from sets import Set as set51+52+53 def _to_tuple(args):54 """55 Return a tuple repr without nested repr.56 """121 unmodified lines178 nodes.IfCondition: self.handle_if_condition,179 nodes.Cycle: self.handle_cycle,180 nodes.Print: self.handle_print,181 nodes.Macro: self.handle_macro,182+ nodes.Call: self.handle_call,183 nodes.Set: self.handle_set,184 nodes.Filter: self.handle_filter,185 nodes.Block: self.handle_block,186 nodes.Include: self.handle_include,205 unmodified lines392 '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'14 unmodified lines421 body_lines.extend([self.handle_node(n) for n in node])422 423 # add body lines and "generator hook"424 lines.extend(body_lines)415- lines.append(' if False:\n yield None')425+ lines.append(' if 0: yield None')426 427 # add the missing blocks428 block_items = blocks.items()429 block_items.sort()7 unmodified lines437 lines.extend([438 '\ndef %s(context):' % func_name,439 ' ctx_push = context.push',440 ' ctx_pop = context.pop',431- ' if False:',432- ' yield None'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)3 unmodified lines449 ))450 451 # blocks must always be defined. even if it's empty. some452 # features depend on it453+ lines.append('\n# Block mapping and debug information')454+ if dict_lines:444- lines.append('\nblocks = {\n%s\n}' % ',\n'.join(dict_lines))455+ lines.append('blocks = {\n%s\n}' % ',\n'.join(dict_lines))456+ else:457+ lines.append('blocks = {}')458 459 # now get the real source lines and map the debugging symbols460 debug_mapping = []461+ file_mapping = {}462 last = None463 offset = -1464 sourcelines = ('\n'.join(lines)).splitlines()465 result = []1 unmodified line467 for idx, line in enumerate(sourcelines):468 m = _debug_re.search(line)469 if m is not None:470 d = m.groupdict()471+ filename = d['filename'] or None472+ if filename in file_mapping:473+ file_id = file_mapping[filename]474+ else:475+ file_id = file_mapping[filename] = 'F%d' % \476+ len(file_mapping)457- this = (d['filename'] or None, int(d['lineno']))477+ this = (file_id, int(d['lineno']))478 # if it's the same as the line before we ignore it479 if this != last:460- debug_mapping.append((idx - offset,) + this)480+ debug_mapping.append('(%r, %s, %r)' % ((idx - offset,) + this))481 last = this482 # for each debug symbol the line number and so the offset483 # changes by one.484 offset += 1485 else:486 result.append(line)487 468- result.append('\ndebug_info = %r' % debug_mapping)488+ # now print file mapping and debug info489+ file_mapping = file_mapping.items()490+ file_mapping.sort(lambda a, b: cmp(a[1], b[1]))491+ for filename, file_id in file_mapping:492+ result.append('%s = %r' % (file_id, filename))493+ result.append('debug_info = [%s]' % ', '.join(debug_mapping))494 return '\n'.join(result)495 496 def handle_template_text(self, node):497 """498 Handle data around nodes.499 """500+ # if we have a ascii only string we go with the501+ # bytestring. otherwise we go with the unicode object502+ try:503+ data = str(node.text)504+ except UnicodeError:505+ data = node.text506 return self.indent(self.nodeinfo(node)) + '\n' +\476- self.indent('yield %r' % node.text)507+ self.indent('yield %r' % data)508 509 def handle_node_list(self, node):510 """511 In some situations we might have a node list. It's just51 unmodified lines563 564 # call recursive for loop!565 if node.recursive:566 write('context[\'loop\'].pop()')536- write('if False:')537- self.indention += 1538- write('yield None')539- self.indention -= 2567+ write('if 0: yield None')568+ self.indention -= 1569 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '570 'buffereater(forloop))')571 write('for item in forloop(%s):' % self.handle_node(node.seq))572 self.indention += 186 unmodified lines659 660 buf = []661 write = lambda x: buf.append(self.indent(x))662 634- write('def macro(*args):')663+ write('def macro(*args, **kw):')664 self.indention += 1665 write(self.nodeinfo(node))666 667+ # collect macro arguments668+ arg_items = []669+ caller_overridden = False670 if node.arguments:671 write('argcount = len(args)')640- tmp = []672 for idx, (name, n) in enumerate(node.arguments):642- tmp.append('\'%s\': (argcount > %d and (args[%d],) '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 ))649- write('ctx_push({%s})' % ', '.join(tmp))680+ if name == 'caller':681+ caller_overridden = True682+ if caller_overridden:683+ write('kw.pop(\'caller\', None)')684 else:651- write('ctx_push()')685+ arg_items.append('\'caller\': kw.pop(\'caller\', Undefined)')686+ write('ctx_push({%s})' % ', '.join(arg_items))687 688+ # disallow any keyword arguments689+ write('if kw:')690+ self.indention += 1691+ write('raise TemplateRuntimeError(\'%s got an unexpected keyword '692+ 'argument %%r\' %% iter(kw).next())' % node.name)693+ self.indention -= 1694+695 write(self.nodeinfo(node.body))696 buf.append(self.handle_node(node.body))697 write('ctx_pop()')656- write('if False:')657- self.indention += 1658- write('yield False')659- self.indention -= 2698+ write('if 0: yield None')699+ self.indention -= 1700 buf.append(self.indent('context[%r] = buffereater(macro)' %701 node.name))702 703 return '\n'.join(buf)704 705+ def handle_call(self, node):706+ """707+ Handle extended macro calls.708+ """709+ buf = []710+ write = lambda x: buf.append(self.indent(x))711+712+ write('def call(**kwargs):')713+ self.indention += 1714+ write('ctx_push(kwargs)')715+ buf.append(self.handle_node(node.body))716+ write('ctx_pop()')717+ write('if 0: yield None')718+ self.indention -= 1719+ write('yield ' + self.handle_call_func(node.expr,720+ {'caller': 'buffereater(call)'}))721+722+ return '\n'.join(buf)723+724 def handle_set(self, node):725 """726 Handle variable assignments.727 """17 unmodified lines745 write('ctx_push()')746 write(self.nodeinfo(node.body))747 buf.append(self.handle_node(node.body))748 write('ctx_pop()')690- write('if False:')691- self.indention += 1692- write('yield None')693- self.indention -= 2749+ write('if 0: yield None')750+ self.indention -= 1751 write('yield %s' % self.filter('buffereater(filtered)()',752 node.filters))753 return '\n'.join(buf)754 175 unmodified lines930 We use the pipe operator for filtering.931 """932 return self.filter(self.handle_node(node.nodes[0]), node.nodes[1:])933 877- def handle_call_func(self, node):934+ def handle_call_func(self, node, extra_kwargs=None):935 """936 Handle function calls.937 """938 args = []7 unmodified lines946 if arg.__class__ is ast.Keyword:947 kwargs[arg.name] = self.handle_node(arg.expr)948 else:949 args.append(self.handle_node(arg))950+ if extra_kwargs:951+ kwargs.update(extra_kwargs) 893- if not (args or kwargs or star_args or dstar_args):952+ if not (args or kwargs or star_args or dstar_args or extra_kwargs):953 return 'call_function_simple(%s, context)' % \954 self.handle_node(node.node)955 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (956 self.handle_node(node.node),149 unmodified linesadded:jinja/_native.py+91 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja._native4+ ~~~~~~~~~~~~~5+6+ This module implements the native base classes in case of not7+ having a jinja with the _speedups module compiled.8+9+ :copyright: 2007 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+from jinja.datastructure import Deferred, Undefined13+14+15+class BaseContext(object):16+17+ def __init__(self, silent, globals, initial):18+ self.silent = silent19+ self.current = current = {}20+ self.stack = [globals, initial, current]21+ self.globals = globals22+ self.initial = initial23+24+ def pop(self):25+ """26+ Pop the last layer from the stack and return it.27+ """28+ rv = self.stack.pop()29+ self.current = self.stack[-1]30+ return rv31+32+ def push(self, data=None):33+ """34+ Push a new dict or empty layer to the stack and return that layer35+ """36+ data = data or {}37+ self.stack.append(data)38+ self.current = self.stack[-1]39+ return data40+41+ def __getitem__(self, name):42+ """43+ Resolve one item. Restrict the access to internal variables44+ such as ``'::cycle1'``. Resolve deferreds.45+ """46+ if not name.startswith('::'):47+ # because the stack is usually quite small we better48+ # use [::-1] which is faster than reversed() in such49+ # a situation.50+ for d in self.stack[::-1]:51+ if name in d:52+ rv = d[name]53+ if rv.__class__ is Deferred:54+ rv = rv(self, name)55+ # never touch the globals!56+ if d is self.globals:57+ self.initial[name] = rv58+ else:59+ d[name] = rv60+ return rv61+ if self.silent:62+ return Undefined63+ raise TemplateRuntimeError('%r is not defined' % name)64+65+ def __setitem__(self, name, value):66+ """67+ Set a variable in the outermost layer.68+ """69+ self.current[name] = value70+71+ def __delitem__(self, name):72+ """73+ Delete an variable in the outermost layer.74+ """75+ if name in self.current:76+ del self.current[name]77+78+ def __contains__(self, name):79+ """80+ Check if the context contains a given variable.81+ """82+ for layer in self.stack:83+ if name in layer:84+ return True85+ return False86+87+ def __len__(self):88+ """89+ Size of the stack.90+ """91+ return len(self.stack)added:jinja/_speedups.c+392 added
1+/**2+ * jinja._speedups3+ * ~~~~~~~~~~~~~~~4+ *5+ * This module implements the BaseContext, a c implementation of the6+ * Context baseclass. If this extension is not compiled the datastructure7+ * module implements a class in python.8+ *9+ * :copyright: 2007 by Armin Ronacher.10+ * :license: BSD, see LICENSE for more details.11+ */12+13+#include <Python.h>14+#include <structmember.h>15+16+static PyObject *Undefined, *TemplateRuntimeError;17+static PyTypeObject *DeferredType;18+19+struct StackLayer {20+ PyObject *dict; /* current value, a dict */21+ struct StackLayer *prev; /* lower struct layer or NULL */22+};23+24+typedef struct {25+ PyObject_HEAD26+ struct StackLayer *globals; /* the dict for the globals */27+ struct StackLayer *initial; /* initial values */28+ struct StackLayer *current; /* current values */29+ long stacksize; /* current size of the stack */30+ int silent; /* boolean value for silent failure */31+} BaseContext;32+33+static int34+init_constants(void)35+{36+ PyObject *datastructure = PyImport_ImportModule("jinja.datastructure");37+ if (!datastructure)38+ return 0;39+ PyObject *exceptions = PyImport_ImportModule("jinja.exceptions");40+ if (!exceptions) {41+ Py_DECREF(datastructure);42+ return 0;43+ }44+ Undefined = PyObject_GetAttrString(datastructure, "Undefined");45+ PyObject *deferred = PyObject_GetAttrString(datastructure, "Deferred");46+ DeferredType = deferred->ob_type;47+ TemplateRuntimeError = PyObject_GetAttrString(exceptions, "TemplateRuntimeError");48+ Py_DECREF(datastructure);49+ Py_DECREF(exceptions);50+ return 1;51+}52+53+static void54+BaseContext_dealloc(BaseContext *self)55+{56+ struct StackLayer *current = self->current, *tmp;57+ while (current) {58+ tmp = current;59+ Py_XDECREF(current->dict);60+ current->dict = NULL;61+ current = tmp->prev;62+ PyMem_Free(tmp);63+ }64+ self->ob_type->tp_free((PyObject*)self);65+}66+67+static int68+BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)69+{70+ PyObject *silent = NULL, *globals = NULL, *initial = NULL;71+72+ static char *kwlist[] = {"silent", "globals", "initial", NULL};73+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", kwlist,74+ &silent, &globals, &initial))75+ return -1;76+ if (!PyDict_Check(globals) || !PyDict_Check(initial)) {77+ PyErr_SetString(PyExc_TypeError, "stack layers must be a dicts.");78+ return -1;79+ }80+81+ self->silent = PyObject_IsTrue(silent);82+83+ self->globals = PyMem_Malloc(sizeof(struct StackLayer));84+ self->globals->dict = globals;85+ Py_INCREF(globals);86+ self->globals->prev = NULL;87+88+ self->initial = PyMem_Malloc(sizeof(struct StackLayer));89+ self->initial->dict = initial;90+ Py_INCREF(initial);91+ self->initial->prev = self->globals;92+93+ self->current = PyMem_Malloc(sizeof(struct StackLayer));94+ self->current->dict = PyDict_New();95+ if (!self->current->dict)96+ return -1;97+ Py_INCREF(self->current->dict);98+ self->current->prev = self->initial;99+100+ self->stacksize = 3;101+ return 0;102+}103+104+static PyObject*105+BaseContext_pop(BaseContext *self)106+{107+ if (self->stacksize <= 3) {108+ PyErr_SetString(PyExc_IndexError, "stack too small.");109+ return NULL;110+ }111+ PyObject *result = self->current->dict;112+ struct StackLayer *tmp = self->current;113+ self->current = tmp->prev;114+ PyMem_Free(tmp);115+ self->stacksize--;116+ return result;117+}118+119+static PyObject*120+BaseContext_push(BaseContext *self, PyObject *args)121+{122+ PyObject *value = NULL;123+ if (!PyArg_ParseTuple(args, "|O:push", &value))124+ return NULL;125+ if (!value) {126+ value = PyDict_New();127+ if (!value)128+ return NULL;129+ }130+ else if (!PyDict_Check(value)) {131+ PyErr_SetString(PyExc_TypeError, "dict required.");132+ return NULL;133+ }134+ else135+ Py_INCREF(value);136+ struct StackLayer *new = malloc(sizeof(struct StackLayer));137+ new->dict = value;138+ new->prev = self->current;139+ self->current = new;140+ self->stacksize++;141+ Py_INCREF(value);142+ return value;143+}144+145+static PyObject*146+BaseContext_getstack(BaseContext *self, void *closure)147+{148+ PyObject *result = PyList_New(self->stacksize);149+ if (!result)150+ return NULL;151+ struct StackLayer *current = self->current;152+ int idx = 0;153+ while (current) {154+ PyList_SetItem(result, idx++, current->dict);155+ Py_INCREF(current->dict);156+ current = current->prev;157+ }158+ PyList_Reverse(result);159+ return result;160+}161+162+static PyObject*163+BaseContext_getcurrent(BaseContext *self, void *closure)164+{165+ Py_INCREF(self->current->dict);166+ return self->current->dict;167+}168+169+static PyObject*170+BaseContext_getinitial(BaseContext *self, void *closure)171+{172+ Py_INCREF(self->initial->dict);173+ return self->initial->dict;174+}175+176+static PyObject*177+BaseContext_getglobals(BaseContext *self, void *closure)178+{179+ Py_INCREF(self->globals->dict);180+ return self->globals->dict;181+}182+183+static int184+BaseContext_readonly(BaseContext *self, PyObject *value, void *closure)185+{186+ PyErr_SetString(PyExc_AttributeError, "can't set attribute");187+ return -1;188+}189+190+static PyObject*191+BaseContext_getitem(BaseContext *self, PyObject *item)192+{193+ if (!PyString_Check(item)) {194+ Py_INCREF(Py_False);195+ return Py_False;196+ }197+198+ /* disallow access to internal jinja values */199+ char *name = PyString_AS_STRING(item);200+ if (strlen(name) >= 2 && name[0] == ':' && name[1] == ':') {201+ Py_INCREF(Py_False);202+ return Py_False;203+ }204+205+ PyObject *result;206+ struct StackLayer *current = self->current;207+ while (current) {208+ result = PyDict_GetItemString(current->dict, name);209+ if (!result) {210+ current = current->prev;211+ continue;212+ }213+ Py_INCREF(result);214+ if (PyObject_TypeCheck(result, DeferredType)) {215+ PyObject *args = PyTuple_New(2);216+ if (!args || !PyTuple_SetItem(args, 0, (PyObject*)self) ||217+ !PyTuple_SetItem(args, 1, item))218+ return NULL;219+220+ PyObject *resolved = PyObject_CallObject(result, args);221+ if (!resolved)222+ return NULL;223+224+ /* never touch the globals */225+ Py_DECREF(result);226+ Py_INCREF(resolved);227+ PyObject *namespace;228+ if (current == self->globals)229+ namespace = self->initial->dict;230+ else231+ namespace = current->dict;232+ PyDict_SetItemString(namespace, name, resolved);233+ return resolved;234+ }235+ return result;236+ }237+238+ if (self->silent) {239+ Py_INCREF(Undefined);240+ return Undefined;241+ }242+ PyErr_Format(TemplateRuntimeError, "'%s' is not defined", name);243+ return NULL;244+}245+246+static int247+BaseContext_contains(BaseContext *self, PyObject *item)248+{249+ if (!PyString_Check(item))250+ return 0;251+252+ char *name = PyString_AS_STRING(item);253+ if (strlen(name) >= 2 && name[0] == ':' && name[1] == ':')254+ return 0;255+256+ struct StackLayer *current = self->current;257+ while (current) {258+ if (!PyMapping_HasKeyString(current->dict, name)) {259+ current = current->prev;260+ continue;261+ }262+ return 1;263+ }264+265+ return 0;266+}267+268+static int269+BaseContext_setitem(BaseContext *self, PyObject *item, PyObject *value)270+{271+ char *name = PyString_AS_STRING(item);272+ if (!value)273+ return PyDict_DelItemString(self->current->dict, name);274+ return PyDict_SetItemString(self->current->dict, name, value);275+}276+277+static PyObject*278+BaseContext_length(BaseContext *self)279+{280+ return PyInt_FromLong(self->stacksize);281+}282+283+static PyGetSetDef BaseContext_getsetters[] = {284+ {"stack", (getter)BaseContext_getstack, (setter)BaseContext_readonly,285+ "a read only copy of the internal stack", NULL},286+ {"current", (getter)BaseContext_getcurrent, (setter)BaseContext_readonly,287+ "reference to the current layer on the stack", NULL},288+ {"initial", (getter)BaseContext_getinitial, (setter)BaseContext_readonly,289+ "reference to the initial layer on the stack", NULL},290+ {"globals", (getter)BaseContext_getglobals, (setter)BaseContext_readonly,291+ "reference to the global layer on the stack", NULL},292+ {NULL} /* Sentinel */293+};294+295+static PyMemberDef BaseContext_members[] = {296+ {NULL} /* Sentinel */297+};298+299+static PyMethodDef BaseContext_methods[] = {300+ {"pop", (PyCFunction)BaseContext_pop, METH_NOARGS,301+ "Pop the highest layer from the stack"},302+ {"push", (PyCFunction)BaseContext_push, METH_VARARGS,303+ "Push one layer to the stack"},304+ {NULL} /* Sentinel */305+};306+307+static PySequenceMethods BaseContext_as_sequence[] = {308+ 0, /* sq_length */309+ 0, /* sq_concat */310+ 0, /* sq_repeat */311+ 0, /* sq_item */312+ 0, /* sq_slice */313+ 0, /* sq_ass_item */314+ 0, /* sq_ass_slice */315+ BaseContext_contains, /* sq_contains */316+ 0, /* sq_inplace_concat */317+ 0 /* sq_inplace_repeat */318+};319+320+static PyMappingMethods BaseContext_as_mapping[] = {321+ (lenfunc)BaseContext_length,322+ (binaryfunc)BaseContext_getitem,323+ (objobjargproc)BaseContext_setitem324+};325+326+static PyTypeObject BaseContextType = {327+ PyObject_HEAD_INIT(NULL)328+ 0, /* ob_size */329+ "jinja._speedups.BaseContext", /* tp_name */330+ sizeof(BaseContext), /* tp_basicsize */331+ 0, /* tp_itemsize */332+ (destructor)BaseContext_dealloc,/* tp_dealloc */333+ 0, /* tp_print */334+ 0, /* tp_getattr */335+ 0, /* tp_setattr */336+ 0, /* tp_compare */337+ 0, /* tp_repr */338+ 0, /* tp_as_number */339+ &BaseContext_as_sequence, /* tp_as_sequence */340+ &BaseContext_as_mapping, /* tp_as_mapping */341+ 0, /* tp_hash */342+ 0, /* tp_call */343+ 0, /* tp_str */344+ 0, /* tp_getattro */345+ 0, /* tp_setattro */346+ 0, /* tp_as_buffer */347+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/348+ "", /* tp_doc */349+ 0, /* tp_traverse */350+ 0, /* tp_clear */351+ 0, /* tp_richcompare */352+ 0, /* tp_weaklistoffset */353+ 0, /* tp_iter */354+ 0, /* tp_iternext */355+ BaseContext_methods, /* tp_methods */356+ BaseContext_members, /* tp_members */357+ BaseContext_getsetters, /* tp_getset */358+ 0, /* tp_base */359+ 0, /* tp_dict */360+ 0, /* tp_descr_get */361+ 0, /* tp_descr_set */362+ 0, /* tp_dictoffset */363+ (initproc)BaseContext_init, /* tp_init */364+ 0, /* tp_alloc */365+ PyType_GenericNew /* tp_new */366+};367+368+static PyMethodDef module_methods[] = {369+ {NULL, NULL, 0, NULL} /* Sentinel */370+};371+372+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */373+#define PyMODINIT_FUNC void374+#endif375+PyMODINIT_FUNC376+init_speedups(void)377+{378+ PyObject *module;379+380+ if (PyType_Ready(&BaseContextType) < 0)381+ return;382+383+ if (!init_constants())384+ return;385+386+ module = Py_InitModule3("_speedups", module_methods, "");387+ if (!module)388+ return;389+390+ Py_INCREF(&BaseContextType);391+ PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);392+}modified:jinja/datastructure.py+31 added-80 removed
178 unmodified lines179 180 jinja_no_finalization = True181 182 183+# import these here because those modules import Deferred and Undefined184+# from this module.185+try:186+ # try to use the c implementation of the base context if available187+ from jinja._speedups import BaseContext188+except ImportError:189+ # if there is no c implementation we go with a native python one190+ from jinja._native import BaseContext191+192+183-class Context(object):193+class Context(BaseContext):194 """195 Dict like object containing the variables for the template.196 """197 198 def __init__(self, _environment_, *args, **kwargs):189- self.environment = _environment_190- self._stack = [_environment_.globals, dict(*args, **kwargs), {}]191- self.globals, self.initial, self.current = self._stack192- self._translate_func = None199+ super(Context, self).__init__(_environment_.silent,200+ _environment_.globals,201+ dict(*args, **kwargs))202 194- # cache object used for filters and tests203+ self._translate_func = None204 self.cache = {}205+ self.environment = _environment_206 197- def translate_func(self):198- """199- Return the translator for this context.200- """201- if self._translate_func is None:202- translator = self.environment.get_translator(self)203- def translate(s, p=None, n=None, r=None):204- if p is None:205- return translator.gettext(s) % (r or {})206- return translator.ngettext(s, p, r[n]) % (r or {})207- self._translate_func = translate208- return self._translate_func209- translate_func = property(translate_func, doc=translate_func.__doc__)210-211- def pop(self):212- """213- Pop the last layer from the stack and return it.214- """215- rv = self._stack.pop()216- self.current = self._stack[-1]217- return rv218-219- def push(self, data=None):220- """221- Push a new dict or empty layer to the stack and return that layer222- """223- data = data or {}224- self._stack.append(data)225- self.current = self._stack[-1]226- return data227-207 def to_dict(self):208 """209 Convert the context into a dict. This skips the globals.210 """211 result = {}233- for layer in self._stack[1:]:212+ for layer in self.stack[1:]:213 for key, value in layer.iteritems():214 if key.startswith('::'):215 continue216 result[key] = value217 return result218 240- def __getitem__(self, name):219+ def translate_func(self):220 """242- Resolve one item. Restrict the access to internal variables243- such as ``'::cycle1'``. Resolve deferreds.221+ Return a translation function for this context. It takes222+ 4 parameters. The singular string, the optional plural one,223+ the indicator number which is used to select the correct224+ plural form and a dict with values which should be inserted.225 """245- if not name.startswith('::'):246- # because the stack is usually quite small we better use [::-1]247- # which is faster than reversed() somehow.248- for d in self._stack[::-1]:249- if name in d:250- rv = d[name]251- if rv.__class__ is Deferred:252- rv = rv(self, name)253- # never touch the globals!254- if d is self.globals:255- self.initial[name] = rv256- else:257- d[name] = rv258- return rv259- if self.environment.silent:260- return Undefined261- raise TemplateRuntimeError('%r is not defined' % name)226+ if self._translate_func is None:227+ translator = self.environment.get_translator(self)228+ def translate(s, p=None, n=None, r=None):229+ if p is None:230+ return translator.gettext(s) % (r or {})231+ return translator.ngettext(s, p, r[n]) % (r or {})232+ self._translate_func = translate233+ return self._translate_func234+ translate_func = property(translate_func, doc=translate_func.__doc__)235 263- def __setitem__(self, name, value):264- """265- Set a variable in the outermost layer.266- """267- self.current[name] = value268-269- def __delitem__(self, name):270- """271- Delete an variable in the outermost layer.272- """273- if name in self.current:274- del self.current[name]275-276- def __contains__(self, name):277- """278- Check if the context contains a given variable.279- """280- for layer in self._stack:281- if name in layer:282- return True283- return False284-236 def __repr__(self):237 """238 String representation of the context.239 """288 unmodified linesmodified:jinja/environment.py+12 added-1 removed
165 unmodified lines166 """167 parser = Parser(self, source, filename)168 return parser.parse()169 170+ def lex(self, source, filename=None):171+ """172+ Lex the given sourcecode and return a generator that yields tokens.173+ The stream returned is not usable for Jinja but can be used if174+ Jinja templates should be processed by other tools (for example175+ syntax highlighting etc)176+177+ The tuples are returned in the form ``(lineno, token, value)``.178+ """179+ return self.lexer.tokeniter(source, filename)180+181 def from_string(self, source):182 """183 Load and parse a template source and translate it into eval-able184 Python code. This code is wrapped within a `Template` class that125 unmodified lines310 any arguments.311 """312 if dyn_args is not None:313 args += tuple(dyn_args)303- elif dyn_kwargs is not None:314+ if dyn_kwargs is not None:315 kwargs.update(dyn_kwargs)316 if getattr(f, 'jinja_unsafe_call', False) or \317 getattr(f, 'alters_data', False):318 return Undefined30 unmodified linesmodified:jinja/lexer.py+2 added-2 removed
49 unmodified lines50 51 operator_re = re.compile('(%s)' % '|'.join([52 isinstance(x, unicode) and str(x) or re.escape(x) for x in [53 # math operators54- '+', '-', '*', '//', '/', '%',54+ '+', '-', '**', '*', '//', '/', '%',55 # braces and parenthesis56 '[', ']', '(', ')', '{', '}',57 # attribute access and comparison / logical operators58 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',4 unmodified lines63 keywords = set(['and', 'block', 'cycle', 'elif', 'else', 'endblock',64 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',65 'endtrans', 'extends', 'filter', 'for', 'if', 'in',66 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',67- 'recursive', 'set', 'trans'])67+ 'recursive', 'set', 'trans', 'print', 'call', 'endcall'])68 69 70 class Failure(object):71 """282 unmodified linesmodified:jinja/nodes.py+23 added-1 removed
218 unmodified lines219 self.body220 )221 222 223+class Call(Node):224+ """225+ A node that represents am extended macro call.226+ """227+228+ def __init__(self, lineno, expr, body):229+ self.lineno = lineno230+ self.expr = expr231+ self.body = body232+233+ def get_items(self):234+ return [self.expr, self.body]235+236+ def __repr__(self):237+ return 'Call(%r, %r)' % (238+ self.expr,239+ self.body240+ )241+242+243 class Set(Node):244 """245 Allow defining own variables.246 """94 unmodified lines341 def get_items(self):342 return [self.template]343 344 def __repr__(self):325- return 'Include(%r)' % self.template345+ return 'Include(%r)' % (346+ self.template347+ )348 349 350 class Trans(Node):351 """24 unmodified linesmodified:jinja/parser.py+40 added-7 removed
39 unmodified lines40 switch_if = StateTest.expect_name('else', 'elif', 'endif')41 end_of_if = StateTest.expect_name('endif')42 end_of_filter = StateTest.expect_name('endfilter')43 end_of_macro = StateTest.expect_name('endmacro')44+end_of_call = StateTest.expect_name('endcall')45 end_of_block_tag = StateTest.expect_name('endblock')46 end_of_trans = StateTest.expect_name('endtrans')47 48 28 unmodified lines77 'set': self.handle_set_directive,78 'filter': self.handle_filter_directive,79 'print': self.handle_print_directive,80 'macro': self.handle_macro_directive,81+ 'call': self.handle_call_directive,82 'block': self.handle_block_directive,83 'extends': self.handle_extends_directive,84 'include': self.handle_include_directive,85 'trans': self.handle_trans_directive177 unmodified lines263 else:264 args = None265 return nodes.Macro(lineno, ast.name, args, body)266 267+ def handle_call_directive(self, lineno, gen):268+ """269+ Handle {% call foo() %}...{% endcall %}270+ """271+ expr = self.parse_python(lineno, gen, '(%s)').expr272+ if expr.__class__ is not ast.CallFunc:273+ raise TemplateSyntaxError('call requires a function or macro '274+ 'call as only argument.', lineno,275+ self.filename)276+ body = self.subparse(end_of_call, True)277+ self.close_remaining_block()278+ return nodes.Call(lineno, expr, body)279+280 def handle_block_directive(self, lineno, gen):281 """282 Handle block directives used for inheritance.283 """35 unmodified lines319 if len(tokens) != 1 or tokens[0][1] != 'string':320 raise TemplateSyntaxError('extends requires a string', lineno,321 self.filename)322 if self.extends is not None:308- raise TemplateSyntaxError('extends called twice', lineno)323+ raise TemplateSyntaxError('extends called twice', lineno,324+ self.filename)325 self.extends = nodes.Extends(lineno, tokens[0][2][1:-1])326 327 def handle_include_directive(self, lineno, gen):328 """329 Handle the include directive used for template inclusion.330 """331 tokens = list(gen)316- if len(tokens) != 1 or tokens[0][1] != 'string':317- raise TemplateSyntaxError('include requires a string', lineno,318- self.filename)319- return nodes.Include(lineno, tokens[0][2][1:-1])332+ # hardcoded include (faster because copied into the bytecode)333+ if len(tokens) == 1 and tokens[0][1] == 'string':334+ return nodes.Include(lineno, str(tokens[0][2][1:-1]))335+ raise TemplateSyntaxError('invalid syntax for include '336+ 'directive. Requires a hardcoded '337+ 'string', lineno,338+ self.filename)339 340 def handle_trans_directive(self, lineno, gen):341 """342 Handle translatable sections.13 unmodified lines356 # check that there are not any more elements357 try:358 gen.next()359 except StopIteration:341- #XXX: what about escapes?342- return nodes.Trans(lineno, data[1:-1], None,360+ # XXX: this looks fishy361+ data = data[1:-1].encode('utf-8').decode('string-escape')362+ return nodes.Trans(lineno, data.decode('utf-8'), None,363 None, None)364 raise TemplateSyntaxError('string based translations '365 'require at most one argument.',366 lineno, self.filename)212 unmodified lines579 raise TemplateSyntaxError('illegal use of keyword %r '580 'as identifier.' % node.name,581 node.lineno, self.filename)582 node.name = node.name[:-1]583+ # same for attributes584 elif node.__class__ is ast.Getattr:585 if not node.attrname.endswith('_'):586 raise TemplateSyntaxError('illegal use of keyword %r '587 'as attribute name.' %588 node.name, node.lineno,589 self.filename)590 node.attrname = node.attrname[:-1]591+ # if we have a ForLoop we ensure that nobody patches existing592+ # object using "for foo.bar in seq"593+ elif node.__class__ is nodes.ForLoop:594+ def check(node):595+ if node.__class__ not in (ast.AssName, ast.AssTuple):596+ raise TemplateSyntaxError('can\'t assign to '597+ 'expression.', node.lineno,598+ self.filename)599+ for n in node.getChildNodes():600+ check(n)601+ check(node.item)602+ # now set the filename and continue working on the childnodes603 node.filename = self.filename604 todo.extend(node.getChildNodes())605 return nodes.Template(self.filename, body, self.extends)606 119 unmodified linesmodified:tests/conftest.py+1 added-1 removed
34 unmodified lines35 name, None, scope))36 37 38 loader = GlobalLoader(globals())39-simple_env = Environment(trim_blocks=True, loader=loader)39+simple_env = Environment(trim_blocks=True, friendly_traceback=False, loader=loader)40 41 42 class Module(py.test.collect.Module):43 19 unmodified linesmodified:tests/test_macros.py+2 added-1 removed
33 unmodified lines34 assert tmpl.render() == 'Hello Peter!'35 36 37 def test_kwargs_failure(env):38+ from jinja.exceptions import TemplateRuntimeError39 tmpl = env.from_string(KWARGSFAILURE)40 try:41 tmpl.render()41- except TypeError, e:42+ except TemplateRuntimeError, e:43 pass44 else:45 raise AssertionError('kwargs failure test failed')46 9 unmodified linesmodified:tests/test_various.py+10 added
32 unmodified lines33 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''34 35 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''36 37+CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''38 39+40 def test_keywords(env):41 env.from_string(KEYWORDS)42 43 16 unmodified lines60 d["a"]61 d["d"] = 462 assert len(d) == 363 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d64+65+66+def test_call():67+ from jinja import Environment68+ env = Environment()69+ env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g70+ tmpl = env.from_string(CALL)71+ assert tmpl.render() == 'abdfh'modified:CHANGES+5 added-1 removed
20 unmodified lines21 - added whitespace management system for the template designer.22 23 - some small bugfixes.24 25-- improved security system regarding function calls.25+- improved security system regarding function calls and variable26+ assignment in for loops.27 28 - added `lipsum` function to generate random text.29 30 - strings without unicode characters are processed as binary strings now33 unmodified lines64 65 - fixed a bug in the parser that didn't unescape keyword arguments. (thanks66 to Alexey Melchakov for reporting)67 68+- You can now use the environment to just tokenize a template. This can69+ be useful for syntax highlighting or other purposes.70 71+72 Version 1.073 -----------74 (released Mar 23, 2007)75 1 unmodified linemodified:setup.py+29 added-2 removed
1 unmodified line2 import jinja3 import os4 import ez_setup5 ez_setup.use_setuptools()6+7+from distutils.command.build_ext import build_ext8+from distutils.errors import CCompilerError6-from setuptools import setup9+from setuptools import setup, Extension, Feature10 from inspect import getdoc11 12 13 def list_files(path):4 unmodified lines18 if os.path.isfile(fn):19 yield fn20 21 22+class optional_build_ext(build_ext):23+24+ def build_extension(self, ext):25+ try:26+ build_ext.build_extension(self, ext)27+ except CCompilerError, e:28+ print '=' * 7929+ print 'INFORMATION'30+ print ' the speedup extension could not be compiled, jinja will'31+ print ' fall back to the native python classes.'32+ print '=' * 7933+34+35+36+37+38 setup(39 name = 'Jinja',40 version = '1.0',41 url = 'http://jinja.pocoo.org/',27 unmodified lines69 entry_points='''70 [python.templating.engines]71 jinja = jinja.plugin:BuffetPlugin72 ''',54- extras_require = {'plugin': ['setuptools>=0.6a2']}73+ extras_require = {'plugin': ['setuptools>=0.6a2']},74+ features = {'speedups': Feature(75+ 'optional C-speed enhancements',76+ standard = True,77+ ext_modules = [78+ Extension('jinja._speedups', ['jinja/_speedups.c'])79+ ]80+ )},81+ cmdclass = {'build_ext': optional_build_ext}82 )added:THANKS+8 added
1+Thanks To2+=========3+4+All the people listed here helped improving Jinja a lot, provided5+patches, helped working out solutions etc. Thanks to all of you!6+7+- Axel Böhm8+- Alexey Melchakovmodified:TODO+4 added-3 removed
1 ===================2 TODO List for Jinja3 ===================4 5-- Requirements in Jinja (blocks and set directives) outside of renderable6- blocks should become part of the module not the generate function.7-5 - Improve the context lookup (maybe with an optional C extension)6+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.