Skip to content
Myr

[svn] checked in changes from the last days regarding jinja, added jinja 1.1 notice for floor divison operator

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 6051814 · Browse files · 9 files+104 added−21 removed
This commit

State

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

Diff stats

9 files+104 added−21 removed

  • other:+104 added−21 removed

9 files+104 added−21 removed

modified:docs/src/designerdoc.txt+18 added-4 removed
86 unmodified lines
87[[list_of_filters]]8889.. admonition:: note9091 Filters have a pretty low priority. If you want to add fitered values92 you have to put them into parentheses. The same applies if you want to access93 attributes:91 The filter operator has a pretty low priority. If you want to add fitered92 values you have to put them into parentheses. The same applies if you want93 to access attributes or return values:9495 .. sourcecode:: jinja9697 correct:
5 unmodified lines
103 {{ (foo|filter).attribute }}104 wrong:105 {{ foo|filter.attribute }}106107*new in Jinja 1.1*:108109Because the application can provide additional filters you can get a documentation110of all the provided filters by calling ``debug.filters()``:111112.. sourcecode:: jinja113114 {{ debug.filters() }}115 -> returns a plain text representation of all the filters116117 {{ debug.filters(False) }}118 -> same as above but without the builtin ones.119120Tests121=====122123You can use the `is` operator to perform tests on a value:
256 unmodified lines
380 ``{{ 1 - 1 }}`` would return ``0``.381 ``/`` divide the left operand by the right one.382 ``{{ 1 / 2 }}`` would return ``0.5``.383 ``//`` divide the left operand by the right one and return a truncated371 integer result: ``{{ 20 // 7 }}`` is ``2``.384 integer result: ``{{ 20 // 7 }}`` is ``2``. (*new in385 Jinja 1.1*)386 ``*`` multiply the left operand with the right one.387 ``{{ 2 * 2 }}`` would return ``4``.388 ``**`` raise the left operand to the power of the right389 operand. ``{{ 2**3 }}`` would return ``8``.
499 unmodified lines
modified:docs/src/devintro.txt+20 added
22 unmodified lines
2324If you receive an error, check if you have a typo in your code. If not, have25a look at the `installation`_ page for troubleshooting.2627Basically the important method on a template is the `render` method. It28takes either a dict or keyword arguments. All keyword arguments appear29in the template as variables.3031So these two snippets do the same:3233.. sourcecode:: python3435 tmpl.render(36 knights='we say nih',37 spam='and eggs'38 )3940.. sourcecode:: python4142 tmpl.render({43 'knights': 'we say nih',44 'spam': 'and eggs'45 })4647The Environment48===============4950[[environment_doc]]
90 unmodified lines
modified:docs/src/index.txt+2 added
28 unmodified lines
29 - `Debugging Support <debugging.txt>`_3031 - `Internationalization <i18n.txt>`_3233 - `Recipies <devrecipies.txt>`_3435- Template Designer Documentation:3637 - `Syntax Reference <designerdoc.txt>`_38
5 unmodified lines
modified:jinja/translators/python.py+6 added-5 removed
414 unmodified lines
415 ' translator = environment.get_translator(context)\n'416 ' def translate(s, p=None, n=None, r=None):\n'417 ' if p is None:\n'418 ' return translator.gettext(s) % (r or {})\n'419 ' return translator.ngettext(s, p, r[n]) % (r or {})'419 ' return translator.ngettext(s, p, r[n]) % (r or {})\n'420 ' context.translate_func = translate'421 )422423 # add body lines and "generator hook"424 lines.extend(body_lines)
160 unmodified lines
585 self.last_cycle_id += 1586 buf = []587 write = lambda x: buf.append(self.indent(x))588588 write('if not %r in context.current:' % name)589 write('if %r not in context.current:' % name)590 self.indention += 1591 write(self.nodeinfo(node))592 if node.seq.__class__ in (ast.Tuple, ast.List):593 write('context.current[%r] = CycleContext(%s)' % (
89 unmodified lines
683 write('if False:')684 self.indention += 1685 write('yield None')686 self.indention -= 2686 write('yield %s' % self.filter('u\'\'.join(filtered())',687 write('yield %s' % self.filter('buffereater(filtered)()',688 node.filters))689 return '\n'.join(buf)690691 def handle_block(self, node, level=0):
42 unmodified lines
734 replacements = '{%s}' % ', '.join(replacements)735 else:736 replacements = 'None'737 return self.indent(self.nodeinfo(node)) + '\n' +\737 self.indent('yield translate(%r, %r, %r, %s)' % (738 self.indent('yield context.translate_func(%r, %r, %r, %s)' % (739 node.singular,740 node.plural,741 node.indicator,742 replacements
8 unmodified lines
751 if node.name in self.constants:752 return self.constants[node.name]753 elif node.name == '_':754 self.require_translations = True754 return 'translate'755 return 'context.translate_func'756 return 'context[%r]' % node.name757758 def handle_compare(self, node):759 """
266 unmodified lines
modified:jinja/datastructure.py+4 added-1 removed
180 unmodified lines
181182183class Context(object):184 """185 Dict like object.185 Dict like object containing the variables for the template.186 """187188 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._stack192193 # translator function added by the environment rendering function194 self.translate_func = None195196 # cache object used for filters and tests197 self.cache = {}198199 def pop(self):
321 unmodified lines
modified:jinja/defaults.py+2 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13from jinja.utils import debug_context, safe_range, generate_lorem_ipsum, \13from jinja.utils import debug_helper, safe_range, generate_lorem_ipsum, \14 watch_changes, flush151617__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']181920DEFAULT_NAMESPACE = {21 'range': safe_range,22 'debug': debug_context,22 'debug': debug_helper,23 'lipsum': generate_lorem_ipsum,24 'watchchanges': watch_changes,25 'flush': flush26}
modified:jinja/parser.py+2 added
472 unmodified lines
473 # objects we do some lazy unicode processing here.474 # if a string is ASCII only we yield it as string475 # in other cases as unicode. This works around476 # problems with datetimeobj.strftime()477 # also escape newlines in strings478 t_data = t_data.replace('\n', '\\n')479 try:480 str(t_data)481 except UnicodeError:482 tokens.append('u' + t_data)
157 unmodified lines
modified:jinja/utils.py+47 added-9 removed
27 unmodified lines
28 from collections import deque29else:30 deque = None3132try:33 set34except NameError:35 from sets import Set as set3637#: number of maximal range items38MAX_RANGE = 10000003940_word_split_re = re.compile(r'(\s+)')
86 unmodified lines
127 raise SecurityException('not allowed attribute accessed')128 return getattr(obj, name)129130126def debug_context(env, context):127 """128 Use this function in templates to get a printed context.129 """130 from pprint import pformat131 return pformat(context.to_dict())132debug_context.jinja_context_callable = True133134131def safe_range(start, stop=None, step=None):132 """133 "Safe" form of range that does not generate too large lists.134 """
230 unmodified lines
365 result.sort(lambda a, b: cmp(a[0], b[0]))366 return result367368369class DebugHelper(object):370 """371 Debugging Helper. Available in the template as "debug".372 """373 jinja_context_callable = True374 jinja_allowed_attributes = ['filters']375376 def __init__(self):377 raise TypeError('cannot create %r instances' %378 self.__class__.__name__)379380 def __call__(self, env, context):381 """Print a nice representation of the context."""382 from pprint import pformat383 return pformat(context.to_dict())384385 def filters(self, env, context, builtins=True):386 """List the filters."""387 from inspect import getdoc388 strip = set()389 if not builtins:390 from jinja.defaults import DEFAULT_FILTERS391 strip = set(DEFAULT_FILTERS.values())392 filters = env.filters.items()393 filters.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))394 result = []395 for name, f in filters:396 if f in strip:397 continue398 doc = '\n'.join(' ' + x for x in (getdoc(f) or '').splitlines())399 result.append('`%s`\n\n%s' % (name, doc))400 return '\n\n'.join(result)401 filters.jinja_context_callable = True402403 def __str__(self):404 print 'use debug() for debugging the context'405406407#: the singleton instance of `DebugHelper`408debug_helper = object.__new__(DebugHelper)409410411class TracebackLoader(object):412 """413 Fake importer that just returns the source of a template.414 """
216 unmodified lines
modified:CHANGES+3 added
30 unmodified lines
3132- added a bunch of new docstrings to the Jinja classes. Makes fun now to33 use pydoc :-)3435- fixed severe memcaching bug. Formerly it wasn't possible to use memcaching36 without enabling disk cache.373839Version 1.040-----------41(released Mar 23, 2007)42
1 unmodified line