Skip to content
Myr

added support for local aliasing of some attributes. the technique used is not very good but covers at least some of the more common use cases

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 9d42abf · Browse files · 3 files+99 added−3 removed
This commit

State

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

Diff stats

3 files+99 added−3 removed

  • other:+99 added−3 removed

3 files+99 added−3 removed

modified:docs/api.rst+29 added
367 unmodified lines
368context. This is the place where you can put variables and functions369that should be available all the time. Additionally :attr:`Template.globals`370exist that are variables available to a specific template that are available371to all :meth:`~Template.render` calls.372373374Jinja2 Semantics375----------------376377Jinja2 behaves like regular Python code in the runtime with some additional378restrictions that allow the template engine to optimize some common idoms.379The context is semi immutable. Only Jinja2 itself may modify it, if other380code (such as :func:`contextfunction`\s) modify it the changes won't show up381as expected.382383Another change to regular Python is that Jinja2 sees attributes as immutable.384It assumes that every time it accesses `foo.bar`, bar will look the same as385long as `foo` was not overriden. In some situations Jinja will take advantage386of that to internally substitute continuous lookups to the same attributes387with a copy of the attribute.388389For example in the following template the `post.user` attribute is looked up390once:391392.. sourcecode:: html+jinja393394 {% if post.user %}395 <h3>{{ post.user.username }}</h3>396 <p>Location: {{ post.user.location }}</p>397 {% endif %}398399That said, the objects passed to the template may not generate different400values every time a property is accessed.
modified:jinja2/compiler.py+67 added-1 removed
105 unmodified lines
106107 # names that are declared by parameters108 self.declared_parameter = set()109110 # static subscribes111 self.static_subscribes = {}112113 def add_special(self, name):114 """Register a special name like `loop`."""115 self.undeclared.discard(name)116 self.declared.add(name)
34 unmodified lines
151152 # the name of the block we're in, otherwise None.153 self.block = parent and parent.block or None154155 # node overlays. see `CodeGenerator.overlay` for more details156 self.overlays = {}157158 # the parent of this frame159 self.parent = parent160161 if parent is not None:162 self.identifiers.declared.update(163 parent.identifiers.declared |164 parent.identifiers.declared_locally |159 parent.identifiers.declared_parameter165 parent.identifiers.declared_parameter |166 parent.identifiers.undeclared167 )168 self.identifiers.outer_undeclared.update(169 parent.identifiers.undeclared -170 self.identifiers.declared
88 unmodified lines
259 elif node.ctx == 'load' and not \260 self.identifiers.is_declared(node.name, self.hard_scope):261 self.identifiers.undeclared.add(node.name)262263 def visit_Subscript(self, node):264 """Under some circumstances subscripts are aliased with local names:265266 - the subscript node is either already aliased or a name that was not267 reassigned.268 - and the subscription argument is a constant string.269 """270 self.generic_visit(node)271 if isinstance(node.arg, nodes.Const) and \272 isinstance(node.arg.value, basestring) and \273 (isinstance(node.node, nodes.Name) and274 node.node.name not in (self.identifiers.declared_locally |275 self.identifiers.declared_parameter)) or \276 node.node in self.identifiers.static_subscribes:277 if node in self.identifiers.static_subscribes:278 self.identifiers.static_subscribes[node] += 1279 else:280 self.identifiers.static_subscribes[node] = 1281282 def visit_Macro(self, node):283 self.generic_visit(node)284 self.identifiers.declared_locally.add(node.name)285
207 unmodified lines
493 touch_comma()494 self.write('**')495 self.visit(node.dyn_kwargs, frame)496497 def overlay(self, node, frame):498 """Visit an overlay and return `True` or `False` if the overlay499 does not exist or is exhausted. An overlay is used to replace a500 node with another one (or an identifier) N times. This is for501 example used to replace static subscribes before reassignments502 of a name that occour more than one time. If a node has overlays503 it's important that this method is called, otherwise the count504 will be out of sync and the generated code is broken.505 """506 if node not in frame.overlays:507 return False508 overlay, count = frame.overlays[node]509 if count is not None and count <= 0:510 return False511 if isinstance(overlay, basestring):512 self.write(overlay)513 else:514 self.visit(overlay, frame)515 frame.overlays[node] = (overlay, count - 1)516 return True517518 def pull_locals(self, frame):519 """Pull all the references identifiers into the local scope."""520 for name in frame.identifiers.undeclared:521 self.writeline('l_%s = context.resolve(%r)' % (name, name))522523 # find all the static subscribes with a count > 2 and524 # order them properly so that subscribes depending on other525 # subscribes are handled later.526 static_subscribes = [(node, count) for node, count in527 frame.identifiers.static_subscribes.items() if528 count >= 2]529 if static_subscribes:530 static_subscribes.sort(key=lambda x: type(x[0].node)531 is nodes.Subscript)532 for node, count in static_subscribes:533 ident = self.temporary_identifier()534 self.writeline(ident + ' = ')535 self.visit(node, frame)536 frame.overlays[node] = (ident, count)537538 def pull_dependencies(self, nodes):539 """Pull all the dependencies."""540 visitor = DependencyFinderVisitor()541 for node in nodes:
783 unmodified lines
1325 self.write(' %s ' % operators[node.op])1326 self.visit(node.expr, frame)13271328 def visit_Subscript(self, node, frame):1329 # subscripts can have overlays1330 if self.overlay(node, frame):1331 return13321333 # slices or integer subscriptions bypass the subscribe1334 # method if we can determine that at compile time.1335 if isinstance(node.arg, nodes.Slice) or \1336 (isinstance(node.arg, nodes.Const) and
87 unmodified lines
modified:jinja2/nodes.py+3 added-2 removed
232 unmodified lines
233 node.frozen = True234 todo.extend(node.iter_child_nodes())235236 def __eq__(self, other):237 return type(self) is type(other) and self.__dict__ == other.__dict__237 return type(self) is type(other) and \238 tuple(self.iter_fields()) == tuple(other.iter_fields())239240 def __ne__(self, other):241 return not self.__eq__(other)242243 def __hash__(self):244 if not self.frozen:245 raise TypeError('unfrozen nodes are unhashable')245 return hash(tuple(self.__dict__.items()))246 return hash(tuple(self.iter_fields()))247248 def __repr__(self):249 return '%s(%s)' % (250 self.__class__.__name__,
554 unmodified lines