added support for dotted names in tests and filters
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 09c002e · Browse files · 5 files·+54 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+54 added−10 removed
- other:+54 added−10 removed
Provenance
- Commit
b9e7875- Tree
d5d79bd- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
09c002e
5 files changed+54 added−10 removed
modified:docs/api.rst+23 added-2 removed
66 unmodified lines67 .. attribute:: filters68 69 A dict of filters for this environment. As long as no template was70 loaded it's safe to add new filters or remove old. For custom filters71- see :ref:`writing-filters`.71+ see :ref:`writing-filters`. For valid filter names have a look at72+ :ref:`identifier-naming`.73 74 .. attribute:: tests75 76 A dict of test functions for this environment. As long as no77 template was loaded it's safe to modify this dict. For custom tests77- see :ref:`writing-tests`.78+ see :ref:`writing-tests`. For valid test names have a look at79+ :ref:`identifier-naming`.80 81 .. attribute:: globals82 83 A dict of global variables. These variables are always available84 in a template and (if the optimizer is enabled) may not be85 overridden by templates. As long as no template was loaded it's safe86 to modify this dict. For more details see :ref:`global-namespace`.87+ For valid object names have a look at :ref:`identifier-naming`.88 89 .. automethod:: overlay([options])90 91 21 unmodified lines113 .. autoclass:: jinja2.environment.TemplateStream114 :members: disable_buffering, enable_buffering115 116 117+.. _identifier-naming:118+119+Notes on Identifiers120+~~~~~~~~~~~~~~~~~~~~121+122+Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to123+match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters124+are currently not allowed. This limitation will probably go away as soon as125+unicode identifiers are fully specified for Python 3.126+127+Filters and tests are looked up in separate namespaces and have slightly128+modified identifier syntax. Filters and tests may contain dots to group129+filters and tests by topic. For example it's perfectly valid to add a130+function into the filter dict and call it `to.unicode`. The regular131+expression for filter and test identifiers is132+``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.133+134+135 Undefined Types136 ---------------137 138 These classes can be used as undefined types. The :class:`Environment`234 unmodified linesmodified:docs/extensions.rst+7 added
100 unmodified lines101 task and usually not needed as the default tags and expressions cover all102 common use cases. The i18n extension is a good example of why extensions are103 useful, another one would be fragment caching.104 105+When writing extensions you have to keep in mind that you are working with the106+Jinja2 template compiler which does not validate the node tree you are possing107+to it. If the AST is malformed you will get all kinds of compiler or runtime108+errors that are horrible to debug. Always make sure you are using the nodes109+you create correctly. The API documentation below shows which nodes exist and110+how to use them.111+112 Example Extension113 ~~~~~~~~~~~~~~~~~114 115 The following example implements a `cache` tag for Jinja2 by using the96 unmodified linesmodified:jinja2/compiler.py+13 added-6 removed
323 unmodified lines324 325 # the current line number326 self.code_lineno = 1327 328+ # registry of all filters and tests (global, not block local)329+ self.tests = {}330+ self.filters = {}331+332 # the debug information333 self.debug_info = []334 self._write_debug_info = None335 140 unmodified lines476 """Pull all the dependencies."""477 visitor = DependencyFinderVisitor()478 for node in nodes:479 visitor.visit(node)476- for name in visitor.filters:477- self.writeline('f_%s = environment.filters[%r]' % (name, name))478- for name in visitor.tests:479- self.writeline('t_%s = environment.tests[%r]' % (name, name))480+ for dependency in 'filters', 'tests':481+ mapping = getattr(self, dependency)482+ for name in getattr(visitor, dependency):483+ if name not in mapping:484+ mapping[name] = self.temporary_identifier()485+ self.writeline('%s = environment.%s[%r]' %486+ (mapping[name], dependency, name))487 488 def collect_shadowed(self, frame):489 """This function returns all the shadowed variables in a dict490 in the form name: alias and will write the required assignments730 unmodified lines1221 self.write(':')1222 self.visit(node.step, frame)1223 1224 def visit_Filter(self, node, frame, initial=None):1218- self.write('f_%s(' % node.name)1225+ self.write(self.filters[node.name] + '(')1226 func = self.environment.filters.get(node.name)1227 if func is None:1228 raise TemplateAssertionError('no filter named %r' % node.name,1229 node.lineno, self.filename)10 unmodified lines1240 self.signature(node, frame)1241 self.write(')')1242 1243 def visit_Test(self, node, frame):1237- self.write('t_%s(' % node.name)1244+ self.write(self.tests[node.name] + '(')1245 if node.name not in self.environment.tests:1246 raise TemplateAssertionError('no test named %r' % node.name,1247 node.lineno, self.filename)1248 self.visit(node.node, frame)32 unmodified linesmodified:jinja2/nodes.py+3 added
725 unmodified lines726 727 class ExtensionAttribute(Expr):728 """Returns the attribute of an extension bound to the environment.729 The identifier is the identifier of the :class:`Extension`.730+731+ This node is usually constructed by calling the732+ :meth:`~jinja2.ext.Extension.attr` method on an extension.733 """734 fields = ('identifier', 'attr')735 736 33 unmodified linesmodified:jinja2/parser.py+8 added-2 removed
674 unmodified lines675 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,676 lineno=token.lineno)677 678 def parse_filter(self, node, start_inline=False):679- lineno = self.stream.current.type679 while self.stream.current.type == 'pipe' or start_inline:680 if not start_inline:681 self.stream.next()682 token = self.stream.expect('name')683+ name = token.value684+ while self.stream.current.type is 'dot':685+ self.stream.next()686+ name += '.' + self.stream.expect('name').value687 if self.stream.current.type is 'lparen':688 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)689 else:690 args = []691 kwargs = []692 dyn_args = dyn_kwargs = None690- node = nodes.Filter(node, token.value, args, kwargs, dyn_args,693+ node = nodes.Filter(node, name, args, kwargs, dyn_args,694 dyn_kwargs, lineno=token.lineno)695 start_inline = False696 return node697 4 unmodified lines702 negated = True703 else:704 negated = False705 name = self.stream.expect('name').value706+ while self.stream.current.type is 'dot':707+ self.stream.next()708+ name += '.' + self.stream.expect('name').value709 dyn_args = dyn_kwargs = None710 kwargs = []711 if self.stream.current.type is 'lparen':712 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)56 unmodified lines