[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
Provenance
- Commit
2acbac1- Tree
b26ef43- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
6051814
9 files changed+104 added−21 removed
modified:docs/src/designerdoc.txt+18 added-4 removed
86 unmodified lines87 [[list_of_filters]]88 89 .. admonition:: note90 91- 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:94 95 .. sourcecode:: jinja96 97 correct:5 unmodified lines103 {{ (foo|filter).attribute }}104 wrong:105 {{ foo|filter.attribute }}106 107+*new in Jinja 1.1*:108+109+Because the application can provide additional filters you can get a documentation110+of all the provided filters by calling ``debug.filters()``:111+112+.. sourcecode:: jinja113+114+ {{ debug.filters() }}115+ -> returns a plain text representation of all the filters116+117+ {{ debug.filters(False) }}118+ -> same as above but without the builtin ones.119+120 Tests121 =====122 123 You can use the `is` operator to perform tests on a value:256 unmodified lines380 ``{{ 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 linesmodified:docs/src/devintro.txt+20 added
22 unmodified lines23 24 If you receive an error, check if you have a typo in your code. If not, have25 a look at the `installation`_ page for troubleshooting.26 27+Basically the important method on a template is the `render` method. It28+takes either a dict or keyword arguments. All keyword arguments appear29+in the template as variables.30+31+So these two snippets do the same:32+33+.. sourcecode:: python34+35+ tmpl.render(36+ knights='we say nih',37+ spam='and eggs'38+ )39+40+.. sourcecode:: python41+42+ tmpl.render({43+ 'knights': 'we say nih',44+ 'spam': 'and eggs'45+ })46+47 The Environment48 ===============49 50 [[environment_doc]]90 unmodified linesmodified:docs/src/index.txt+2 added
28 unmodified lines29 - `Debugging Support <debugging.txt>`_30 31 - `Internationalization <i18n.txt>`_32 33+ - `Recipies <devrecipies.txt>`_34+35 - Template Designer Documentation:36 37 - `Syntax Reference <designerdoc.txt>`_38 5 unmodified linesmodified:jinja/translators/python.py+6 added-5 removed
414 unmodified lines415 ' 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 )422 423 # add body lines and "generator hook"424 lines.extend(body_lines)160 unmodified lines585 self.last_cycle_id += 1586 buf = []587 write = lambda x: buf.append(self.indent(x))588 588- 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 lines683 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)690 691 def handle_block(self, node, level=0):42 unmodified lines734 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 replacements8 unmodified lines751 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.name757 758 def handle_compare(self, node):759 """266 unmodified linesmodified:jinja/datastructure.py+4 added-1 removed
180 unmodified lines181 182 183 class Context(object):184 """185- Dict like object.185+ Dict like object containing the variables for the template.186 """187 188 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 193+ # translator function added by the environment rendering function194+ self.translate_func = None195+196 # cache object used for filters and tests197 self.cache = {}198 199 def pop(self):321 unmodified linesmodified:jinja/defaults.py+2 added-2 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13-from jinja.utils import debug_context, safe_range, generate_lorem_ipsum, \13+from jinja.utils import debug_helper, safe_range, generate_lorem_ipsum, \14 watch_changes, flush15 16 17 __all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']18 19 20 DEFAULT_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 lines473 # 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 linesmodified:jinja/utils.py+47 added-9 removed
27 unmodified lines28 from collections import deque29 else:30 deque = None31 32+try:33+ set34+except NameError:35+ from sets import Set as set36+37 #: number of maximal range items38 MAX_RANGE = 100000039 40 _word_split_re = re.compile(r'(\s+)')86 unmodified lines127 raise SecurityException('not allowed attribute accessed')128 return getattr(obj, name)129 130 126-def 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())132-debug_context.jinja_context_callable = True133-134-131 def safe_range(start, stop=None, step=None):132 """133 "Safe" form of range that does not generate too large lists.134 """230 unmodified lines365 result.sort(lambda a, b: cmp(a[0], b[0]))366 return result367 368 369+class DebugHelper(object):370+ """371+ Debugging Helper. Available in the template as "debug".372+ """373+ jinja_context_callable = True374+ jinja_allowed_attributes = ['filters']375+376+ def __init__(self):377+ raise TypeError('cannot create %r instances' %378+ self.__class__.__name__)379+380+ def __call__(self, env, context):381+ """Print a nice representation of the context."""382+ from pprint import pformat383+ return pformat(context.to_dict())384+385+ 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 = True402+403+ def __str__(self):404+ print 'use debug() for debugging the context'405+406+407+#: the singleton instance of `DebugHelper`408+debug_helper = object.__new__(DebugHelper)409+410+411 class TracebackLoader(object):412 """413 Fake importer that just returns the source of a template.414 """216 unmodified linesmodified:CHANGES+3 added
30 unmodified lines31 32 - added a bunch of new docstrings to the Jinja classes. Makes fun now to33 use pydoc :-)34 35+- fixed severe memcaching bug. Formerly it wasn't possible to use memcaching36+ without enabling disk cache.37 38+39 Version 1.040 -----------41 (released Mar 23, 2007)42 1 unmodified line