Skip to content
Myr

improved variable exporting, added TODO file

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 1de4c64 · Browse files · 6 files+123 added−13 removed
This commit

State

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

Diff stats

6 files+123 added−13 removed

  • other:+123 added−13 removed

6 files+123 added−13 removed

modified:docs/jinjaext.py+6 added-3 removed
166 unmodified lines
167 doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '')168 if node.abstract:169 members = []170 for key, name in node.__dict__.iteritems():171 if not key.startswith('_') and callable(name):171 if not key.startswith('_') and \172 not hasattr(node.__base__, key) and callable(name):173 members.append(key)174 if members:175 members.sort()176 doc.append('%s :members: %s' % (p, ', '.join(members)), '')176 else:177 if node.__base__ != object:178 doc.append('', '')178 doc.append(p + ' :Node type: :class:`%s`' % node.__base__.__name__, '')179 doc.append('%s :Node type: :class:`%s`' %180 (p, node.__base__.__name__), '')181 # XXX: sphinx bug? Expr gives a rst warning182 doc.append('', '')183 children = node.__subclasses__()184 children.sort(key=lambda x: x.__name__.lower())185 for child in children:
10 unmodified lines
modified:docs/tricks.rst+2 added-2 removed
63 unmodified lines
6465The layout template can then access `active_page`. Additionally it makes66sense to defined a default for that variable::6768 {% navigation_bar = [68 {% set navigation_bar = [69 ('/', 'index', 'Index'),70 ('/downloads/', 'downloads', 'Downloads'),71 ('/about/', 'about', 'About')72 ] -%}73 {% active_page = active_page|default('index') -%}73 {% set active_page = active_page|default('index') -%}74 ...75 <ul id="navigation">76 {% for href, id, caption in navigation_bar %}77 <li{% if id == active_page %} class="active"{% endif
4 unmodified lines
modified:jinja2/compiler.py+19 added-3 removed
41 unmodified lines
42def generate(node, environment, name, filename, stream=None):43 """Generate the python source for a node tree."""44 if not isinstance(node, nodes.Template):45 raise TypeError('Can\'t compile non template nodes')46 node.freeze()47 generator = CodeGenerator(environment, name, filename, stream)48 generator.visit(node)49 if stream is None:50 return generator.stream.getvalue()
1087 unmodified lines
1138 self.visit(node.node, frame)11391140 # make sure toplevel assignments are added to the context.1141 if frame.toplevel:1141 for name in assignment_frame.assigned_names:1142 public_names = [x for x in assignment_frame.assigned_names1143 if not x.startswith('__')]1144 if len(assignment_frame.assigned_names) == 1:1145 name = iter(assignment_frame.assigned_names).next()1146 self.writeline('context.vars[%r] = l_%s' % (name, name))1143 if not name.startswith('__'):1144 self.writeline('context.exported_vars.add(%r)' % name)1147 else:1148 self.writeline('context.vars.update({')1149 for idx, name in enumerate(assignment_frame.assigned_names):1150 if idx:1151 self.write(', ')1152 self.write('%r: l_%s' % (name, name))1153 self.write('})')1154 if public_names:1155 if len(public_names) == 1:1156 self.writeline('context.exported_vars.add(%r)' %1157 public_names[0])1158 else:1159 self.writeline('context.exported_vars.update((%s))' %1160 ', '.join(map(repr, public_names)))11611162 def visit_Name(self, node, frame):1163 if node.ctx == 'store' and frame.toplevel:1164 frame.assigned_names.add(node.name)
189 unmodified lines
modified:jinja2/ext.py+5 added-5 removed
75 unmodified lines
76 raise NotImplementedError()7778 def attr(self, name, lineno=None):79 """Return an attribute node for the current extension. This is useful80 to pass callbacks to template code::80 to pass constants on extensions to generated template code::8182 nodes.Call(self.attr('_my_callback'), args, kwargs, None, None)8384 That would call `self._my_callback` when the template is evaluated.82 self.attr('_my_attribute', lineno=lineno)83 """84 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)8586 def call_method(self, name, args=None, kwargs=None, dyn_args=None,87 dyn_kwargs=None, lineno=None):90 """Call a method of the extension."""88 """Call a method of the extension. This is a shortcut for89 :meth:`attr` + :class:`jinja2.nodes.Call`.90 """91 if args is None:92 args = []93 if kwargs is None:94 kwargs = []
269 unmodified lines
modified:jinja2/nodes.py+34 added
88 unmodified lines
89 positional arguments, attributes as keyword arguments. Each node has90 two attributes: `lineno` (the line number of the node) and `environment`.91 The `environment` attribute is set at the end of the parsing process for92 all nodes automatically.9394 Nodes can be frozen which makes them hashable. The compiler freezes the95 nodes automatically. Modifications on frozen nodes are possible but not96 allowed.97 """98 __metaclass__ = NodeType99 fields = ()100 attributes = ('lineno', 'environment')101 abstract = True102 frozen = False103104 def __init__(self, *fields, **attributes):105 if self.abstract:106 raise TypeError('abstract nodes are not instanciable')107 if fields:108 if len(fields) != len(self.fields):109 if not self.fields:110 raise TypeError('%r takes 0 arguments' %
108 unmodified lines
219 node.environment = environment220 todo.extend(node.iter_child_nodes())221 return self222223 def freeze(self):224 """Freeze the complete node tree which makes them hashable.225 This happens automatically on compilation. Frozen nodes must not be226 modified any further. Extensions may not freeze nodes that appear227 in the final node tree (ie: nodes that are returned from the extension228 parse method).229 """230 todo = deque([self])231 while todo:232 node = todo.popleft()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__238239 def __ne__(self, other):240 return not self.__eq__(other)241242 def __hash__(self):243 if not self.frozen:244 raise TypeError('unfrozen nodes are unhashable')245 return hash(tuple(self.__dict__.items()))246247 def __repr__(self):248 return '%s(%s)' % (249 self.__class__.__name__,250 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
153 unmodified lines
404class BinExpr(Expr):405 """Baseclass for all binary expressions."""406 fields = ('left', 'right')407 operator = None408 abstract = True409410 def as_const(self):411 f = _binop_to_func[self.operator]412 try:
5 unmodified lines
418class UnaryExpr(Expr):419 """Baseclass for all unary expressions."""420 fields = ('node',)421 operator = None422 abstract = True423424 def as_const(self):425 f = _uaop_to_func[self.operator]426 try:
17 unmodified lines
444445446class Literal(Expr):447 """Baseclass for literals."""448 abstract = True449450451class Const(Literal):452 """All constant values. The parser will return this node for simple
351 unmodified lines
added:TODO+57 added
1Todo Before Release2===================34This has to be implemented before the release:56Drop special casing template globals7------------------------------------89The idea some time ago was to partially evaluate templates at compile time.10For that we decided to not allow globals being overridden by locals as the11static compiler could have changed semantics. Turns out that the static12compiler blows up the complexity to something nobody wants to support which13means that this restriction is kinda pointless.1415That should go for good.1617Pull Attributes Onces18---------------------1920Imagine the following template::2122 {% if foo.bar %}23 {{ baz(foo.bar) }}24 {% endif %}2526Problem with that is that it compiles to this::2728 if environment.subscribe(l_foo, 'bar'):29 if 0: yield None30 yield u'\n %s\n' % (31 l_baz(environment.subscribe(l_foo, 'bar')),32 )3334As `environment.subscribe` is more expensive then regular attribute lookups35(it tries getitem/getattr and in sandbox mode also permissions) multiple36lookups with the same parameters in the same scope should get local aliases.37The result we have is that one::3839 t1 = environment.subscribe(l_foo, 'bar')40 if t1:41 if 0: yield None42 yield u'\n %s\n' % (43 l_baz(t1),44 )4546However that should only happen if the attribute is accessed multiple times47unlike locals and filters/tests which are always pulled. We're not doing that48for filters/tests/locals as nested scopes may access it and testing is too49complicated for the tiny performance improvement but easy for attribute50lookups, keeping the complexity of the whole thing in mind.5152Use `set` for Assignments53-------------------------5455The keyword-less way to assign variabeles is a left-over from the days when56it was possible to use Jinja2 like a regular programming language without57necessary template end/start delimiters to group statements.