Skip to content
Myr

[svn] again some jinja updates, some minor performance and doc improvements

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 b475cff · Browse files · 12 files+236 added−95 removed
This commit

State

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

Diff stats

12 files+236 added−95 removed

  • tests:+60 added−7 removed
  • other:+176 added−88 removed

12 files+236 added−95 removed

modified:docs/src/builtins.txt+9 added
172 unmodified lines
173 is checked.174175 *new in Jinja 1.1*176177`rendertemplate`178179 Loads and renders a template with a copy of the current context. This works180 in many situations like the ``{% include %}`` tag, just that it does not181 include a template and merges it into the template structure but renders182 it completely independent and returns the rendered data as string.183184 *new in Jinja 1.1*185186187Global Constants188================189190Jinja provides some special variables which cannot be overridden in templates.
22 unmodified lines
modified:docs/src/designerdoc.txt+67 added-60 removed
349 unmodified lines
350351For information regarding the visibility of macros have a look at the352`Scopes and Variable Behavior`_ section.353354Extended Macro Call355===================356357*new in Jinja 1.1*358359Jinja 1.1 adds a new special tag that you can use to pass some evaluable360template code to a macro. Here an example macro that uses the features of361the ``{% call %}`` tag:362363.. sourcecode:: html+jinja364365 {% macro dialog title %}366 <div class="dialog">367 <h3>{{ title }}</h3>368 <div class="text">369 {{ caller() }}370 </div>371 </div>372 {% endmacro %}373374Called the normal way `caller` will be undefined, but if you call it375using the new `{% call %}` tag you can pass it some data:376377.. sourcecode:: html+jinja378379 {% call dialog('Hello World') %}380 This is an example dialog381 {% endcall %}382383Now the data wrapped will be inserted where you put the `caller` call.384385If you pass `caller()` some keyword arguments those are added to the386namespace of the wrapped template data:387388.. sourcecode:: html+jinja389390 {% macro makelist items %}391 <ul>392 {%- for item in items %}393 <li>{{ caller(item=item) }}</li>394 {%- endfor %}395 </ul>396 {%- endmacro %}397398 {% call makelist([1, 2, 3, 4, 5, 6]) -%}399 [[{{ item }}]]400 {%- endcall %}401402This will then produce this output:403404.. sourcecode:: html405406 <ul>407 <li>[[1]]</li>408 <li>[[2]]</li>409 <li>[[3]]</li>410 <li>[[4]]</li>411 <li>[[5]]</li>412 <li>[[6]]</li>413 </ul>414415416Template Inclusion417==================418419You can load another template at a given position using ``{% include %}``.
15 unmodified lines
435436This is intended because it makes it possible to include macros from other437templates.438439*new in Jinja 1.1* you can now render an included template to a string that is440evaluated in an indepdendent environment by calling `rendertemplate`. See the441documentation for this function in the `builtins`_ documentation.442443Filtering Blocks444================445446Sometimes it could be a good idea to filter a complete block of text. For
60 unmodified lines
507 {{ macro_('foo') }}508 {% endfor %}509510445Bleeding Edge446=============447448Here are some features documented that are new in the SVN version and might449change.450451``{% call %}``:452453 A new tag that allows to pass a macro a block with template data:454455 .. sourcecode:: html+jinja456457 {% macro dialog title %}458 <div class="dialog">459 <h3>{{ title }}</h3>460 <div class="text">461 {{ caller() }}462 </div>463 </div>464 {% endmacro %}465466 Called the normal way `caller` will be undefined, but if you call it467 using the new `{% call %}` tag you can pass it some data:468469 .. sourcecode:: html+jinja470471 {% call dialog('Hello World') %}472 This is an example dialog473 {% endcall %}474475 If you pass `caller()` some keyword arguments those are added to the476 namespace of the wrapped template data:477478 .. sourcecode:: html+jinja479480 {% macro makelist items %}481 <ul>482 {%- for item in items %}483 <li>{{ caller(item=item) }}</li>484 {%- endfor %}485 </ul>486 {%- endmacro %}487488 {% call makelist([1, 2, 3, 4, 5, 6]) -%}489 [[{{ item }}]]490 {%- endcall %}491492 This will then produce this output:493494 .. sourcecode:: html495496 <ul>497 <li>[[1]]</li>498 <li>[[2]]</li>499 <li>[[3]]</li>500 <li>[[4]]</li>501 <li>[[5]]</li>502 <li>[[6]]</li>503 </ul>504511.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice512.. _Scopes and Variable Behavior: scopes.txt513.. _builtins: builtins.txt
modified:docs/src/filters.txt+12 added
55 unmodified lines
5657If you're using Jinja with django and want to use the django filters in Jinja58have a look at the `developer recipies`_ page.5960*new in Jinja 1.1* additionally to the `stringfilter` decorator there is now61a similar decorator that works exactly the same but does not convert values62to unicode:6364.. sourcecode:: python6566 from jinja.filters import simplefilter6768 @simplefilter69 def do_add(value, to_add):70 return value + to_add7172.. _designer documentation: builtins.txt73.. _developer recipies: devrecipies.txt
modified:jinja/translators/python.py+6 added-6 removed
222 unmodified lines
223224 #: mapping of unsupported syntax elements.225 #: the value represents the feature name that appears226 #: in the exception.227 self.unsupported = {228 ast.ListComp: 'list comprehensions'229 }227 self.unsupported = {ast.ListComp: 'list comprehension'}228229 #: because of python2.3 compatibility add generator230 #: expressions only to the list of unused features231 #: if it exists.232 if hasattr(ast, 'GenExpr'):235 self.unsupported.update({236 ast.GenExpr: 'generator expressions'237 })233 self.unsupported[ast.GenExpr] = 'generator expression'234235 #: if expressions are unsupported too (so far)236 if hasattr(ast, 'IfExp'):237 self.unsupported[ast.IfExp] = 'inline if expression'238239 # -- public methods240241 def process(environment, node):242 """
973 unmodified lines
modified:jinja/environment.py+12 added-8 removed
20 unmodified lines
2122__all__ = ['Environment']232425#: minor speedup26_getattr = getattr272829class Environment(object):30 """31 The Jinja environment.32
263 unmodified lines
296 return get_attribute(obj, name)297 except (AttributeError, SecurityException):298 pass299 if obj is self.undefined_singleton:296 return getattr(self.undefined_singleton, name)300 return _getattr(obj, name)301 return self.undefined_singleton302303 def get_attributes(self, obj, attributes):304 """
13 unmodified lines
318 if dyn_args is not None:319 args += tuple(dyn_args)320 if dyn_kwargs is not None:321 kwargs.update(dyn_kwargs)318 if getattr(f, 'jinja_unsafe_call', False) or \319 getattr(f, 'alters_data', False):322 if _getattr(f, 'jinja_unsafe_call', False) or \323 _getattr(f, 'alters_data', False):324 return self.undefined_singleton321 if getattr(f, 'jinja_context_callable', False):325 if _getattr(f, 'jinja_context_callable', False):326 args = (self, context) + args327 return f(*args, **kwargs)328329 def call_function_simple(self, f, context):330 """331 Function call without arguments. Because of the smaller signature and332 fewer logic here we have a bit of redundant code.333 """330 if getattr(f, 'jinja_unsafe_call', False) or \331 getattr(f, 'alters_data', False):334 if _getattr(f, 'jinja_unsafe_call', False) or \335 _getattr(f, 'alters_data', False):336 return self.undefined_singleton333 if getattr(f, 'jinja_context_callable', False):337 if _getattr(f, 'jinja_context_callable', False):338 return f(self, context)339 return f()340341 def finish_var(self, value, ctx):
5 unmodified lines
347 if value is None:348 return u''349 elif value is self.undefined_singleton:350 return unicode(value)347 elif getattr(value, 'jinja_no_finalization', False):351 elif _getattr(value, 'jinja_no_finalization', False):352 return value353 val = self.to_unicode(value)354 if self.default_filters:355 val = self.apply_filters(val, ctx, self.default_filters)
1 unmodified line
modified:jinja/filters.py+40 added-5 removed
9 unmodified lines
10"""11import re12from random import choice13from urllib import urlencode, quote14from jinja.utils import urlize, escape, reversed14from jinja.utils import urlize, escape, reversed, sorted15from jinja.datastructure import TemplateData16from jinja.exceptions import FilterArgumentError171819_striptags_re = re.compile(r'(<!--.*?-->|<[^>]+>)')202122def stringfilter(f):23 """24 Decorator for filters that just work on unicode objects.25 """
12 unmodified lines
38 pass39 return decorator404142def simplefilter(f):43 """44 Decorator for simplifying filters. Filter arguments are passed45 to the decorated function without environment and context. The46 source value is the first argument. (like stringfilter but47 without unicode conversion)48 """49 def decorator(*args):50 def wrapped(env, context, value):51 return f(value, *args)52 return wrapped53 try:54 decorator.__doc__ = f.__doc__55 decorator.__name__ = f.__name__56 except:57 pass58 return decorator596061def do_replace(s, old, new, count=None):62 """63 Return a copy of the value with all occurrences of a substring64 replaced with a new one. The first argument is the substring
84 unmodified lines
149 <ul class="my_list" id="list-42">150 ...151 </ul>152131 As you can see it automatically appends a space in front of the item153 As you can see it automatically prepends a space in front of the item154 if the filter returned something. You can disable this by passing155 `false` as only argument to the filter.156157 *New in Jinja 1.1*
531 unmodified lines
689 return value690 return wrapped691692671def do_striptags(value, rex=re.compile(r'<[^>]+>')):693def do_striptags(value):694 """695 Strip SGML/XML tags and replace adjacent whitespace by one space.696697 *new in Jinja 1.1*698 """677 return ' '.join(rex.sub('', value).split())699 return ' '.join(_striptags_re.sub('', value).split())700do_striptags = stringfilter(do_striptags)701702703def do_slice(slices, fill_with=None):
135 unmodified lines
839 return func(value)840 return wrapped841842843def do_sort(reverse=False):844 """845 Sort a sequence. Per default it sorts ascending, if you pass it846 `True` as first argument it will reverse the sorting.847848 *new in Jinja 1.1*849 """850 def wrapped(env, context, value):851 return sorted(value, reverse=reverse)852 return wrapped853854855FILTERS = {856 'replace': do_replace,857 'upper': do_upper,858 'lower': do_lower,
37 unmodified lines
896 'slice': do_slice,897 'batch': do_batch,898 'sum': do_sum,899 'abs': do_abs,866 'round': do_round900 'round': do_round,901 'sort': do_sort902}
modified:jinja/utils.py+24 added-8 removed
37 unmodified lines
38 return list.pop(self, 0)39 def clear(self):40 del self[:]4142# support for a working reversed()42# support for a working reversed() in 2.343try:44 reversed = reversed45except NameError:46 def reversed(iterable):
3 unmodified lines
50 return iter(iterable[::-1])51 except TypeError:52 return iter(tuple(iterable)[::-1])5354# support for python 2.3/2.454# set support for python 2.355try:56 set = set57except NameError:58 from sets import Set as set5960# sorted support (just a simplified version)61try:62 sorted = sorted63except NameError:64 def sorted(seq, reverse=False):65 rv = list(seq)66 rv.sort(reverse=reverse)67 return rv6869#: function types70callable_types = (FunctionType, MethodType)717273#: number of maximal range items74MAX_RANGE = 10000007576_word_split_re = re.compile(r'(\s+)')
76 unmodified lines
153 _from_string_env = Environment()154 return _from_string_env.from_string(source)155156157#: minor speedup158_getattr = getattr159160def get_attribute(obj, name):161 """162 Return the attribute from name. Raise either `AttributeError`163 or `SecurityException` if something goes wrong.164 """165 if not isinstance(name, basestring):166 raise AttributeError(name)151 if name[:2] == name[-2:] == '__' or name[:2] == '::':167 if name[:2] == name[-2:] == '__':168 raise SecurityException('not allowed to access internal attributes')153 if (obj.__class__ is FunctionType and name.startswith('func_') or154 obj.__class__ is MethodType and name.startswith('im_')):169 if obj.__class__ in callable_types and name.startswith('func_') or \170 name.startswith('im_'):171 raise SecurityException('not allowed to access function attributes')156 r = getattr(obj, 'jinja_allowed_attributes', None)172 r = _getattr(obj, 'jinja_allowed_attributes', None)173 if r is not None and name not in r:158 raise SecurityException('not allowed attribute accessed')159 return getattr(obj, name)174 raise SecurityException('disallowed attribute accessed')175 return _getattr(obj, name)176177178def safe_range(start, stop=None, step=None):179 """
520 unmodified lines
modified:tests/test_filters.py+9 added-1 removed
59 unmodified lines
60ROUND = '''{{ 2.7|round }}|{{ 2.1|round }}|\61{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''62XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,63'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''64SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''65666768def test_capitalize(env):69 tmpl = env.from_string(CAPITALIZE)70 assert tmpl.render() == 'Foo bar'71
43 unmodified lines
115116def test_striptags(env):117 tmpl = env.from_string(STRIPTAGS)118 out = tmpl.render(foo=' <p>just a small \n <a href="#">'117 'example</a> link</p>\n<p>to a webpage</p>')119 'example</a> link</p>\n<p>to a webpage</p> '120 '<!-- <p>and some commented stuff</p> -->')121 assert out == 'just a small example link to a webpage'122123124def test_filesizeformat(env):
151 unmodified lines
276 assert len(out) == 3277 assert 'foo="42"' in out278 assert 'bar="23"' in out279 assert 'blub:blub="&lt;?&gt;"' in out280281282def test_sort(env):283 tmpl = env.from_string(SORT)284 assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
modified:tests/test_forloop.py+6 added
16 unmodified lines
17CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\18{% for item in seq %}{% cycle through %}{% endfor %}'''19SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''20VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}'''21NONITER = '''{% for item in none %}...{% endfor %}'''222324def test_simple(env):25 tmpl = env.from_string(SIMPLE)
47 unmodified lines
73 yield item74 tmpl = env.from_string(VARLEN)75 output = tmpl.render(iter=inner())76 assert output == '01234'777879def test_noniter(env):80 tmpl = env.from_string(NONITER)81 assert not tmpl.render()
modified:tests/test_macros.py+31 added
37 unmodified lines
38{% macro test %}{{ varargs|join('|') }}{% endmacro %}\39{{ test(1, 2, 3) }}\40'''4142SIMPLECALL = '''\43{% macro test %}[[{{ caller() }}]]{% endmacro %}\44{% call test() %}data{% endcall %}\45'''4647COMPLEXCALL = '''\48{% macro test %}[[{{ caller(data='data') }}]]{% endmacro %}\49{% call test() %}{{ data }}{% endcall %}\50'''5152CALLERUNDEFINED = '''\53{% set caller = 42 %}\54{% macro test() %}{{ caller is not defined }}{% endmacro %}\55{{ test() }}\56'''575859def test_simple(env):60 tmpl = env.from_string(SIMPLE)61 assert tmpl.render() == 'Hello Peter!'62
26 unmodified lines
8990def test_varargs(env):91 tmpl = env.from_string(VARARGS)92 assert tmpl.render() == '1|2|3'939495def test_simple_call(env):96 tmpl = env.from_string(SIMPLECALL)97 assert tmpl.render() == '[[data]]'9899100def test_complex_call(env):101 tmpl = env.from_string(COMPLEXCALL)102 assert tmpl.render() == '[[data]]'103104105def test_caller_undefined(env):106 tmpl = env.from_string(CALLERUNDEFINED)107 assert tmpl.render() == 'True'
modified:tests/test_various.py+14 added-6 removed
5 unmodified lines
6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910KEYWORDS = '''10KEYWORDS = '''\11{{ with }}12{{ as }}13{{ import }}14{{ from }}
11 unmodified lines
26{{ raise }}27{{ yield }}28{{ while }}29{{ pass }}30{{ finally }}31'''3230{{ finally }}'''31UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''3432RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''3633CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''343536def test_keywords(env):
27 unmodified lines
64 env = Environment()65 env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g66 tmpl = env.from_string(CALL)67 assert tmpl.render() == 'abdfh'686970def test_stringfilter(env):71 from jinja.filters import stringfilter72 f = stringfilter(lambda f, x: f + x)73 assert f('42')(env, None, 23) == '2342'747576def test_simplefilter(env):77 from jinja.filters import simplefilter78 f = simplefilter(lambda f, x: f + x)79 assert f(42)(env, None, 23) == 65
modified:CHANGES+6 added-1 removed
53 unmodified lines
54- fixed a bug that allowed users to override the special names `_`, `true` etc.5556- added `batch` and `slice` filters for batching or slicing sequences5758- added `sum`, `abs` and `round` filters. This fixes #23858- added `sum`, `abs`, `round` and `sort` filters. This fixes #2385960- added `striptags` and `xmlattr` filters for easier SGML/XML processing6162- the trans tag does not need explicit naming for variables with the same
39 unmodified lines
102- It's now possible to iterate over iterators additionally to sequences.103 If the iterator is inifite it will crash however, so makes sure you don't104 pass something like that to a template!105106- added `rendetemplate` to render included templates in an isolated107 environment and get the outout back.108109- added `simplefilter` decorator.110111112Version 1.0113-----------114(released Mar 23, 2007)115
1 unmodified line