Skip to content
Myr

[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

22 files+791 added−321 removed

deleted:docs/src/contextenv.txt-173 removed
1=======================2Context and Environment3=======================45The two central objects in Jinja are the `Environment` and `Context`. Both6are designed to be subclassed by applications if they need to extend Jinja.78Environment9===========1011The initialization parameters are already covered in the `Quickstart`_ thus12not repeated here.1314But beside those configurable instance variables there are some functions used15in the template evaluation code you may want to override:1617**def** `to_unicode` *(self, value)*:1819 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.2223 Also `None` is converted into an empty string per default.2425**def** `get_translator` *(self, context)*:2627 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`_.3233 If you don't provide a translator a default one is used to switch34 between singular and plural forms.3536 Have a look at the `i18n`_ section for more information.3738**def** `get_translations` *(self, name)*:3940 Get the translations for the template `name`. Only works if a loader41 is present. See the `i18n`_ section for more details.4243**def** `get_translations_for_string` *(self, string)*:4445 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.4849**def** `apply_filters` *(self, value, context, filters)*:5051 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:5657 .. sourcecode:: python5859 [('escape', ()), ('replace', (u'a', u'b'))]6061 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.6566 **Warning** this is a Jinja internal method. The actual implementation67 and function signature might change.6869**def** `perform_test` *(self, context, testname, args, value, invert)*:7071 Like `apply_filters` you usually don't override this one. It's the72 callback function for tests (``foo is bar`` / ``foo is not bar``).7374 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.7879 Missing tests should raise a `TestNotFound` exception.8081 **Warning** this is a Jinja internal method. The actual implementation82 and function signature might change.8384**def** `get_attribute` *(self, obj, attribute)*:8586 Get `attribute` from the object provided. The default implementation87 performs security tests.8889 **Warning** this is a Jinja internal method. The actual implementation90 and function signature might change.9192**def** `get_attributes` *(self, obj, attributes)*:9394 Get some attributes from the object. If `attributes` is an empty95 sequence the object itself is returned unchanged.9697**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.103104 The default implementation performs some security checks.105106 **Warning** this is a Jinja internal method. The actual implementation107 and function signature might change.108109**def** `call_function_simple` *(self, f, context)*:110111 Like `call_function` but without arguments.112113 **Warning** this is a Jinja internal method. The actual implementation114 and function signature might change.115116**def** `finish_var` *(self, value, ctx)*:117118 Postprocess a variable before it's sent to the template.119120 **Warning** this is a Jinja internal method. The actual implementation121 and function signature might change.122 123.. admonition:: Note124125 The Enviornment class is defined in `jinja.environment.Environment`126 but imported into the `jinja` package because it's often used.127128Context129=======130131Jinja wraps the variables passed to the template in a special class called a132context. This context supports variables on multiple layers and lazy (deferred)133objects. Often your application has a request object, database connection134object or something similar you want to access in filters, functions etc.135136Beacause of that you can easily subclass a context to add additional variables137or to change the way it behaves.138139**def** `pop` *(self)*:140141 Pop the outermost layer and return it.142143**def** `push` *(self, data=None)*:144145 Push a dict to the stack or an empty layer.146147 Has to return the pushed object.148149**def** `to_dict` *(self)*:150151 Flatten the context and convert it into a dict.152153**def** `__getitem__` *(self, name)*:154155 Resolve an item. Per default this also resolves `Deferred` objects.156157**def** `__setitem__` *(self, name, value)*:158159 Set an item in the outermost layer.160161**def** `__delitem__` *(self, name)*:162163 Delete an item in the outermost layer. Do not raise exceptions if164 the value does not exist.165166**def** `__contains__` *(self, name)*:167168 Return `True` if `name` exists in the context.169170171.. _i18n: i18n.txt172.. _Quickstart: devintro.txt173.. _gettext documentation: http://docs.python.org/lib/module-gettext.html
modified:docs/src/designerdoc.txt+1 added-1 removed
782 unmodified lines
783784 `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`788789If you want to use such a name you have to prefix or suffix it or use790alternative names:791
149 unmodified lines
modified:docs/src/devintro.txt+5 added
55 unmodified lines
56``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 lines
modified:docs/src/index.txt+31 added-18 removed
4 unmodified lines
5Welcome in the Jinja documentation.67- `Installing Jinja <installation.txt>`_89- Application Developer Documentation:9- **Application Developer Documentation**:1011 - `Quickstart <devintro.txt>`_11 - `Quickstart <devintro.txt>`_ - getting started with Jinja1213 - `Template Loaders <loaders.txt>`_13 - `Template Loaders <loaders.txt>`_ - documentation for the different14 loader types and how to write custom ones.1515 - `Filter Functions <filters.txt>`_16 - `Filter Functions <filters.txt>`_ - information about how to write17 custom filter functions.1817 - `Test Functions <tests.txt>`_19 - `Test Functions <tests.txt>`_ - information about how to write20 custom test functions.2119 - `Global Objects <objects.txt>`_22 - `Global Objects <objects.txt>`_ - information about the special global23 namespace in Jinja templates.2421 - `Streaming Interface <streaming.txt>`_25 - `Streaming Interface <streaming.txt>`_ - using Jinja for big templates26 by streaming the output.2723 - `Context and Environment <contextenv.txt>`_28 - `Internationalization <i18n.txt>`_ - how to internationalize applications29 using Jinja templates.3025 - `Translators <translators.txt>`_31 - `Alternative Syntax <altsyntax.txt>`_ - changing the default Jinja32 block / variable / comment delimiters.3327 - `Framework Integration <frameworks.txt>`_34 - `API Documentation <api.txt>`_ - API documentation for public Jinja35 objects like `Environment`.3629 - `Debugging Support <debugging.txt>`_37 - `Translators <translators.txt>`_ - explanation about the Jinja template38 translation interface.3931 - `Internationalization <i18n.txt>`_40 - `Framework Integration <frameworks.txt>`_ - integrating Jinja into41 python frameworks.4233 - `Alternative Syntax <altsyntax.txt>`_43 - `Debugging Support <debugging.txt>`_ - debugging Jinja templates.4435 - `Developer Recipies <devrecipies.txt>`_45 - `Developer Recipies <devrecipies.txt>`_ - tips and tricks for application46 developers.4737- Template Designer Documentation:48- **Template Designer Documentation**:4939 - `Syntax Reference <designerdoc.txt>`_50 - `Syntax Reference <designerdoc.txt>`_ - the designer documentation. Put51 this under your pillow.5241 - `Differences To Django <fromdjango.txt>`_53 - `Differences To Django <fromdjango.txt>`_ - coming from django? Then this54 document is for you.5543 - `Designer Recipies <recipies.txt>`_56 - `Designer Recipies <recipies.txt>`_ - various tips and tricks for designers.5758- `Changelog <changelog.txt>`_5960There is also support via IRC on the ``#pocoo`` channel on `irc.freenode.net`.
modified:docs/src/objects.txt+2 added
72 unmodified lines
73The function is always called with the same arguments. The first one is the74current environment, the second the context and the third is the name of the75variable. In this example ``recent_comments``.7677The value is cached until rendering/streaming finished.7879Unsafe Methods / Attributes80===========================8182Because Jinja is sandboxed it provides several ways to prevent unsafe attribute
48 unmodified lines
modified:docs/src/recipies.txt+13 added
167 unmodified lines
168 <body>169 <div class="head">{{ title }}</div>170 </body>171 </html>172173174Vim Syntax Highlighting175=======================176177Because of the similar syntax to django you can use the django highlighting178plugin for jinja too. There is however a Jinja syntax highlighting plugin179too which supports all of the syntax elements.180181You can download it from the vim webpage: `jinja.vim`_182183184.. _jinja.vim: http://www.vim.org/scripts/script.php?script_id=1856
modified:docs/src/translators.txt+3 added-3 removed
3 unmodified lines
45Jinja translates the template sourcecode into executable python code behind6the secenes. This is done by the python translator which is currently the7only shipped translator. Because the interface isn't stable it's also not8recommended yet to write other translators. However for the next Jinja version9a JavaScript translator is planned which allows you to translate Jinja10templates into executable JavaScript code.8recommended yet to write other translators. However for one of the next Jinja9versions a JavaScript translator is planned which allows you to translate10Jinja templates into executable JavaScript code.
modified:jinja/translators/python.py+86 added-27 removed
42 unmodified lines
43 class GeneratorExit(Exception):44 """For python2.3/python2.4 compatibility"""454647try:48 set49except NameError:50 from sets import Set as set515253def _to_tuple(args):54 """55 Return a tuple repr without nested repr.56 """
121 unmodified lines
178 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 lines
392 'call_function', 'call_function_simple', 'finish_var']]393394 # bootstrapping code395 lines = [396 '# Essential imports\n'397 'from __future__ import division\n'398 'from jinja.datastructure import Undefined, LoopContext, '399 'CycleContext, SuperBlock\n'400 'from jinja.utils import buffereater\n'401 'from jinja.exceptions import TemplateRuntimeError\n\n'402 '# Local aliases for some speedup\n'403 '%s\n'404 '__name__ = %r\n\n'405 'def generate(context):\n'406 ' assert environment is context.environment\n'
14 unmodified lines
421 body_lines.extend([self.handle_node(n) for n in node])422423 # 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')426427 # add the missing blocks428 block_items = blocks.items()429 block_items.sort()
7 unmodified lines
437 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 lines
449 ))450451 # 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 = {}')458459 # 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 line
467 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)487468 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)495496 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)508509 def handle_node_list(self, node):510 """511 In some situations we might have a node list. It's just
51 unmodified lines
563564 # 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 += 1
86 unmodified lines
659660 buf = []661 write = lambda x: buf.append(self.indent(x))662634 write('def macro(*args):')663 write('def macro(*args, **kw):')664 self.indention += 1665 write(self.nodeinfo(node))666667 # 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))687688 # 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 -= 1694695 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))702703 return '\n'.join(buf)704705 def handle_call(self, node):706 """707 Handle extended macro calls.708 """709 buf = []710 write = lambda x: buf.append(self.indent(x))711712 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)'}))721722 return '\n'.join(buf)723724 def handle_set(self, node):725 """726 Handle variable assignments.727 """
17 unmodified lines
745 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 lines
930 We use the pipe operator for filtering.931 """932 return self.filter(self.handle_node(node.nodes[0]), node.nodes[1:])933877 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 lines
946 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 lines
added:jinja/_native.py+91 added
1# -*- coding: utf-8 -*-2"""3 jinja._native4 ~~~~~~~~~~~~~56 This module implements the native base classes in case of not7 having a jinja with the _speedups module compiled.89 :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from jinja.datastructure import Deferred, Undefined131415class BaseContext(object):1617 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 = initial2324 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 rv3132 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 data4041 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)6465 def __setitem__(self, name, value):66 """67 Set a variable in the outermost layer.68 """69 self.current[name] = value7071 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]7778 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 False8687 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 */1213#include <Python.h>14#include <structmember.h>1516static PyObject *Undefined, *TemplateRuntimeError;17static PyTypeObject *DeferredType;1819struct StackLayer {20 PyObject *dict; /* current value, a dict */21 struct StackLayer *prev; /* lower struct layer or NULL */22};2324typedef 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;3233static int34init_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}5253static void54BaseContext_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}6667static int68BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)69{70 PyObject *silent = NULL, *globals = NULL, *initial = NULL;7172 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 }8081 self->silent = PyObject_IsTrue(silent);8283 self->globals = PyMem_Malloc(sizeof(struct StackLayer));84 self->globals->dict = globals;85 Py_INCREF(globals);86 self->globals->prev = NULL;8788 self->initial = PyMem_Malloc(sizeof(struct StackLayer));89 self->initial->dict = initial;90 Py_INCREF(initial);91 self->initial->prev = self->globals;9293 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;99100 self->stacksize = 3;101 return 0;102}103104static PyObject*105BaseContext_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}118119static PyObject*120BaseContext_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}144145static PyObject*146BaseContext_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}161162static PyObject*163BaseContext_getcurrent(BaseContext *self, void *closure)164{165 Py_INCREF(self->current->dict);166 return self->current->dict;167}168169static PyObject*170BaseContext_getinitial(BaseContext *self, void *closure)171{172 Py_INCREF(self->initial->dict);173 return self->initial->dict;174}175176static PyObject*177BaseContext_getglobals(BaseContext *self, void *closure)178{179 Py_INCREF(self->globals->dict);180 return self->globals->dict;181}182183static int184BaseContext_readonly(BaseContext *self, PyObject *value, void *closure)185{186 PyErr_SetString(PyExc_AttributeError, "can't set attribute");187 return -1;188}189190static PyObject*191BaseContext_getitem(BaseContext *self, PyObject *item)192{193 if (!PyString_Check(item)) {194 Py_INCREF(Py_False);195 return Py_False;196 }197198 /* 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 }204205 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;219220 PyObject *resolved = PyObject_CallObject(result, args);221 if (!resolved)222 return NULL;223224 /* 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 }237238 if (self->silent) {239 Py_INCREF(Undefined);240 return Undefined;241 }242 PyErr_Format(TemplateRuntimeError, "'%s' is not defined", name);243 return NULL;244}245246static int247BaseContext_contains(BaseContext *self, PyObject *item)248{249 if (!PyString_Check(item))250 return 0;251252 char *name = PyString_AS_STRING(item);253 if (strlen(name) >= 2 && name[0] == ':' && name[1] == ':')254 return 0;255256 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 }264265 return 0;266}267268static int269BaseContext_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}276277static PyObject*278BaseContext_length(BaseContext *self)279{280 return PyInt_FromLong(self->stacksize);281}282283static 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};294295static PyMemberDef BaseContext_members[] = {296 {NULL} /* Sentinel */297};298299static 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};306307static 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};319320static PyMappingMethods BaseContext_as_mapping[] = {321 (lenfunc)BaseContext_length,322 (binaryfunc)BaseContext_getitem,323 (objobjargproc)BaseContext_setitem324};325326static 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};367368static PyMethodDef module_methods[] = {369 {NULL, NULL, 0, NULL} /* Sentinel */370};371372#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */373#define PyMODINIT_FUNC void374#endif375PyMODINIT_FUNC376init_speedups(void)377{378 PyObject *module;379380 if (PyType_Ready(&BaseContextType) < 0)381 return;382383 if (!init_constants())384 return;385386 module = Py_InitModule3("_speedups", module_methods, "");387 if (!module)388 return;389390 Py_INCREF(&BaseContextType);391 PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);392}
modified:jinja/datastructure.py+31 added-80 removed
178 unmodified lines
179180 jinja_no_finalization = True181182183# import these here because those modules import Deferred and Undefined184# from this module.185try:186 # try to use the c implementation of the base context if available187 from jinja._speedups import BaseContext188except ImportError:189 # if there is no c implementation we go with a native python one190 from jinja._native import BaseContext191192183class Context(object):193class Context(BaseContext):194 """195 Dict like object containing the variables for the template.196 """197198 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))202194 # cache object used for filters and tests203 self._translate_func = None204 self.cache = {}205 self.environment = _environment_206197 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__)210211 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 rv218219 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 data227207 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 result218240 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__)235263 def __setitem__(self, name, value):264 """265 Set a variable in the outermost layer.266 """267 self.current[name] = value268269 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]275276 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 False284236 def __repr__(self):237 """238 String representation of the context.239 """
288 unmodified lines
modified:jinja/environment.py+12 added-1 removed
165 unmodified lines
166 """167 parser = Parser(self, source, filename)168 return parser.parse()169170 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)176177 The tuples are returned in the form ``(lineno, token, value)``.178 """179 return self.lexer.tokeniter(source, filename)180181 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 that
125 unmodified lines
310 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 Undefined
30 unmodified lines
modified:jinja/lexer.py+2 added-2 removed
49 unmodified lines
5051operator_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 lines
63keywords = 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'])686970class Failure(object):71 """
282 unmodified lines
modified:jinja/nodes.py+23 added-1 removed
218 unmodified lines
219 self.body220 )221222223class Call(Node):224 """225 A node that represents am extended macro call.226 """227228 def __init__(self, lineno, expr, body):229 self.lineno = lineno230 self.expr = expr231 self.body = body232233 def get_items(self):234 return [self.expr, self.body]235236 def __repr__(self):237 return 'Call(%r, %r)' % (238 self.expr,239 self.body240 )241242243class Set(Node):244 """245 Allow defining own variables.246 """
94 unmodified lines
341 def get_items(self):342 return [self.template]343344 def __repr__(self):325 return 'Include(%r)' % self.template345 return 'Include(%r)' % (346 self.template347 )348349350class Trans(Node):351 """
24 unmodified lines
modified:jinja/parser.py+40 added-7 removed
39 unmodified lines
40switch_if = StateTest.expect_name('else', 'elif', 'endif')41end_of_if = StateTest.expect_name('endif')42end_of_filter = StateTest.expect_name('endfilter')43end_of_macro = StateTest.expect_name('endmacro')44end_of_call = StateTest.expect_name('endcall')45end_of_block_tag = StateTest.expect_name('endblock')46end_of_trans = StateTest.expect_name('endtrans')4748
28 unmodified lines
77 '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_directive
177 unmodified lines
263 else:264 args = None265 return nodes.Macro(lineno, ast.name, args, body)266267 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)279280 def handle_block_directive(self, lineno, gen):281 """282 Handle block directives used for inheritance.283 """
35 unmodified lines
319 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])326327 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)339340 def handle_trans_directive(self, lineno, gen):341 """342 Handle translatable sections.
13 unmodified lines
356 # 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 lines
579 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 lines
modified:tests/conftest.py+1 added-1 removed
34 unmodified lines
35 name, None, scope))363738loader = GlobalLoader(globals())39simple_env = Environment(trim_blocks=True, loader=loader)39simple_env = Environment(trim_blocks=True, friendly_traceback=False, loader=loader)404142class Module(py.test.collect.Module):43
19 unmodified lines
modified:tests/test_macros.py+2 added-1 removed
33 unmodified lines
34 assert tmpl.render() == 'Hello Peter!'353637def 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 lines
modified:tests/test_various.py+10 added
32 unmodified lines
33UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''3435RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''3637CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''383940def test_keywords(env):41 env.from_string(KEYWORDS)4243
16 unmodified lines
60 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 d646566def 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 lines
21- added whitespace management system for the template designer.2223- some small bugfixes.2425- improved security system regarding function calls.25- improved security system regarding function calls and variable26 assignment in for loops.2728- added `lipsum` function to generate random text.2930- strings without unicode characters are processed as binary strings now
33 unmodified lines
6465- fixed a bug in the parser that didn't unescape keyword arguments. (thanks66 to Alexey Melchakov for reporting)6768- You can now use the environment to just tokenize a template. This can69 be useful for syntax highlighting or other purposes.707172Version 1.073-----------74(released Mar 23, 2007)75
1 unmodified line
modified:setup.py+29 added-2 removed
1 unmodified line
2import jinja3import os4import ez_setup5ez_setup.use_setuptools()67from distutils.command.build_ext import build_ext8from distutils.errors import CCompilerError6from setuptools import setup9from setuptools import setup, Extension, Feature10from inspect import getdoc111213def list_files(path):
4 unmodified lines
18 if os.path.isfile(fn):19 yield fn202122class optional_build_ext(build_ext):2324 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 '=' * 79333435363738setup(39 name = 'Jinja',40 version = '1.0',41 url = 'http://jinja.pocoo.org/',
27 unmodified lines
69 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
1Thanks To2=========34All the people listed here helped improving Jinja a lot, provided5patches, helped working out solutions etc. Thanks to all of you!67- Axel Böhm8- Alexey Melchakov
modified:TODO+4 added-3 removed
1===================2TODO List for Jinja3===================45- Requirements in Jinja (blocks and set directives) outside of renderable6 blocks should become part of the module not the generate function.75- Improve the context lookup (maybe with an optional C extension)67- `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.