Skip to content
Myr

Automated merge with ssh://dev.pocoo.org/jinja2-main

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

--HG-- branch : trunk

authored by Christoph Hack · committed by Christoph Hack · parents e9e43bb, 62f8a29 · Browse files · 6 files+180 added−33 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+180 added−33 removed

  • other:+180 added−33 removed

6 files+180 added−33 removed

added:examples/inheritance.py+12 added
1from jinja2 import Environment2from jinja2.loaders import DictLoader345env = Environment(loader=DictLoader({6'a': '''[A[{% block body %}{% endblock %}]]''',7'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',8'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''9}))101112print env.get_template('c').render()
modified:jinja2/compiler.py+91 added-18 removed
37 unmodified lines
383940def generate(node, environment, filename, stream=None):41 """Generate the python source for a node tree."""42 is_child = node.find(nodes.Extends) is not None43 generator = CodeGenerator(environment, is_child, filename, stream)42 generator = CodeGenerator(environment, filename, stream)43 generator.visit(node)44 if stream is None:45 return generator.stream.getvalue()46
65 unmodified lines
112 """Holds compile time information for us."""113114 def __init__(self, parent=None):115 self.identifiers = Identifiers()116117 # a toplevel frame is the root + soft frames such as if conditions.118 self.toplevel = False119120 # the root frame is basically just the outermost frame, so no if121 # conditions. This information is used to optimize inheritance122 # situations.123 self.rootlevel = False123 self.parent = parent124125 # inside some tags we are using a buffer rather than yield statements.126 # this for example affects {% filter %} or {% macro %}. If a frame127 # is buffered this variable points to the name of the list used as128 # buffer.129 self.buffer = None130131 # if a frame has name_overrides, all read access to a name in this132 # dict is redirected to a string expression.133 self.name_overrides = {}134135 # the name of the block we're in, otherwise None.136 self.block = parent and parent.block or None137138 # the parent of this frame139 self.parent = parent140141 if parent is not None:142 self.identifiers.declared.update(143 parent.identifiers.declared |144 parent.identifiers.declared_locally |
82 unmodified lines
227228229class CodeGenerator(NodeVisitor):230217 def __init__(self, environment, is_child, filename, stream=None):231 def __init__(self, environment, filename, stream=None):232 if stream is None:233 stream = StringIO()234 self.environment = environment221 self.is_child = is_child235 self.filename = filename236 self.stream = stream237238 # a registry for all blocks. Because blocks are moved out239 # into the global python scope they are registered here240 self.blocks = {}225 self.indentation = 0226 self.new_lines = 0227 self.last_identifier = 0241242 # the number of extends statements so far243 self.extends_so_far = 0244245 # some templates have a rootlevel extends. In this case we246 # can safely assume that we're a child template and do some247 # more optimizations.248 self.has_known_extends = False249250 # the number of new lines before the next write()251 self._new_lines = 0252253 # the line number of the last written statement254 self._last_line = 0255256 # true if nothing was written so far.257 self._first_write = True258259 # used by the `temporary_identifier` method to get new260 # unique, temporary identifier261 self._last_identifier = 0262263 # the current indentation264 self._indentation = 0265266 def temporary_identifier(self):267 """Get a new unique identifier."""234 self.last_identifier += 1235 return 't%d' % self.last_identifier268 self._last_identifier += 1269 return 't%d' % self._last_identifier270271 def indent(self):272 """Indent by one."""238 self.indentation += 1273 self._indentation += 1274275 def outdent(self, step=1):276 """Outdent by step."""241 self.indentation -= step277 self._indentation -= step278279 def blockvisit(self, nodes, frame, indent=True, force_generator=True):280 """Visit a list of nodes as block in a frame. Per default the281 code is indented, but this can be disabled by setting the indent282 parameter to False. If the current frame is no buffer a dummy283 ``if 0: yield None`` is written automatically unless the284 force_generator parameter is set to False.285 """286 if indent:287 self.indent()288 if frame.buffer is None and force_generator:289 self.writeline('if 0: yield None')
5 unmodified lines
295 if indent:296 self.outdent()297298 def write(self, x):299 """Write a string into the output stream."""257 if self.new_lines:300 if self._new_lines:301 if not self._first_write:259 self.stream.write('\n' * self.new_lines)302 self.stream.write('\n' * self._new_lines)303 self._first_write = False261 self.stream.write(' ' * self.indentation)262 self.new_lines = 0304 self.stream.write(' ' * self._indentation)305 self._new_lines = 0306 self.stream.write(x)307308 def writeline(self, x, node=None, extra=0):309 """Combination of newline and write."""310 self.newline(node, extra)311 self.write(x)312313 def newline(self, node=None, extra=0):314 """Add one or more newlines before the next write."""270 self.new_lines = max(self.new_lines, 1 + extra)315 self._new_lines = max(self._new_lines, 1 + extra)316 if node is not None and node.lineno != self._last_line:317 self.write('# line: %s' % node.lineno)273 self.new_lines = 1318 self._new_lines = 1319 self._last_line = node.lineno320321 def signature(self, node, frame, have_comma=True, extra_kwargs=None):322 """Writes a function call to the stream for the current node.323 Per default it will write a leading comma but this can be324 disabled by setting have_comma to False. If extra_kwargs is325 given it must be a string that represents a single keyword326 argument call that is inserted at the end of the regular327 keyword argument calls.328 """329 have_comma = have_comma and [True] or []330 def touch_comma():331 if have_comma:332 self.write(', ')
18 unmodified lines
351 self.write('**')352 self.visit(node.dyn_kwargs, frame)353354 def pull_locals(self, frame, indent=True):355 """Pull all the references identifiers into the local scope.356 This affects regular names, filters and tests. If indent is357 set to False, no automatic indentation will take place.358 """359 if indent:360 self.indent()361 for name in frame.identifiers.undeclared:362 self.writeline('l_%s = context[%r]' % (name, name))
4 unmodified lines
367 if indent:368 self.outdent()369370 def collect_shadowed(self, frame):371 """This function returns all the shadowed variables in a dict372 in the form name: alias and will write the required assignments373 into the current scope. No indentation takes place.374 """375 # make sure we "backup" overridden, local identifiers376 # TODO: we should probably optimize this and check if the377 # identifier is in use afterwards.378 aliases = {}
2 unmodified lines
381 self.writeline('%s = l_%s' % (ident, name))382 return aliases383384 def function_scoping(self, node, frame):385 """In Jinja a few statements require the help of anonymous386 functions. Those are currently macros and call blocks and in387 the future also recursive loops. As there is currently388 technical limitation that doesn't allow reading and writing a389 variable in a scope where the initial value is coming from an390 outer scope, this function tries to fall back with a common391 error message. Additionally the frame passed is modified so392 that the argumetns are collected and callers are looked up.393394 This will return the modified frame.395 """396 func_frame = frame.inner()397 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)398399 # variables that are undeclared (accessed before declaration) and
90 unmodified lines
490 for name, block in self.blocks.iteritems():491 block_frame = Frame()492 block_frame.inspect(block.body)493 block_frame.block = name494 block_frame.identifiers.add_special('super')495 block_frame.name_overrides['super'] = 'context.super(%r)' % name496 self.writeline('def block_%s(context, environment=environment):'497 % name, block, 1)498 self.pull_locals(block_frame)499 self.blockvisit(block.body, block_frame)
531 unmodified lines
modified:jinja2/environment.py+42 added-8 removed
30 unmodified lines
31 comment_start_string='{#',32 comment_end_string='#}',33 line_statement_prefix=None,34 trim_blocks=False,35 optimized=True,36 loader=None):37 """Here the possible initialization parameters:3839 ========================= ============================================
12 unmodified lines
52 documentation for more details.53 `trim_blocks` If this is set to ``True`` the first newline54 after a block is removed (block, not55 variable tag!). Defaults to ``False``.56 `optimized` should the optimizer be enabled? Default is57 ``True``.58 `loader` the loader which should be used.59 ========================= ============================================60 """61
5 unmodified lines
67 self.comment_start_string = comment_start_string68 self.comment_end_string = comment_end_string69 self.line_statement_prefix = line_statement_prefix70 self.trim_blocks = trim_blocks71 self.optimized = optimized7273 # defaults74 self.filters = DEFAULT_FILTERS.copy()75 self.tests = DEFAULT_TESTS.copy()
28 unmodified lines
104 The tuples are returned in the form ``(lineno, token, value)``.105 """106 return self.lexer.tokeniter(source, filename)107104 def compile(self, source, filename=None, raw=False):108 def compile(self, source, filename=None, raw=False, globals=None):109 """Compile a node or source."""110 if isinstance(source, basestring):111 source = self.parse(source, filename)112 if self.optimized:108 node = optimize(source, self)113 node = optimize(source, self, globals or {})114 source = generate(node, self, filename)115 if raw:116 return source117 if isinstance(filename, unicode):
5 unmodified lines
123 relative to the loader root, but if the paths should be relative this124 function can be used to calculate the real filename."""125 return template126122 def get_template(self, name, parent=None):127 def get_template(self, name, parent=None, globals=None):128 """Load a template."""129 if self.loader is None:130 raise TypeError('no loader for this environment specified')131 if parent is not None:132 name = self.join_path(name, parent)133 globals = self.make_globals(globals)128 return self.loader.load(self, name)134 return self.loader.load(self, name, globals)135130 def from_string(self, source, filename='<string>'):136 def from_string(self, source, filename='<string>', globals=None):137 """Load a template from a string."""138 globals = self.make_globals(globals)132 return Template(self, self.compile(source, filename))139 return Template(self, self.compile(source, filename), globals)140141 def make_globals(self, d):142 """Return a dict for the globals."""143 if d is None:144 return self.globals145 return dict(self.globals, **d)146147148class Template(object):149 """Represents a template."""150151 def __init__(self, environment, code):
4 unmodified lines
156 self.environment = environment157 self.name = namespace['filename']158 self.root_render_func = namespace['root']159 self.blocks = namespace['blocks']160 self.globals = globals161162 def render(self, *args, **kwargs):149 return u''.join(self.stream(*args, **kwargs))163 return u''.join(self.generate(*args, **kwargs))164165 def stream(self, *args, **kwargs):152 gen = self.root_render_func(dict(*args, **kwargs))166 return TemplateStream(self.generate(*args, **kwargs))167168 def generate(self, *args, **kwargs):169 # assemble the context170 context = self.globals.copy()171 context.update(*args, **kwargs)172173 # if the environment is using the optimizer locals may never174 # override globals as optimizations might have happened175 # depending on values of certain globals. This assertion goes176 # away if the python interpreter is started with -O177 if __debug__ and self.environment.optimized:178 overrides = set(context) & set(self.globals)179 if overrides:180 plural = len(overrides) != 1 and 's' or ''181 raise AssertionError('the per template variable%s %s '182 'override%s global variable%s. '183 'With an enabled optimizer this '184 'will lead to unexpected results.' %185 (plural, ', '.join(overrides), plural or ' a', plural))186 gen = self.root_render_func(context)187 # skip the first item which is a reference to the stream188 gen.next()189 return gen
modified:jinja2/loaders.py+3 added-3 removed
17 unmodified lines
1819 def get_source(self, environment, template):20 raise TemplateNotFound()2122 def load(self, environment, template):22 def load(self, environment, template, globals=None):23 source, filename = self.get_source(environment, template)24 code = environment.compile(source, filename)25 return Template(environment, code)24 code = environment.compile(source, filename, globals=globals)25 return Template(environment, code, globals or {})262728class FileSystemLoader(BaseLoader):29
30 unmodified lines
modified:jinja2/optimizer.py+2 added-1 removed
247 unmodified lines
248 lineno=node.lineno,249 environment=self.environment)250 except nodes.Impossible:251 return node252253 visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \254 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \255 visit_Not = visit_Compare = visit_Subscript = visit_Call = \255 visit_Filter = visit_Test = fold256 visit_Filter = visit_Test = visit_CondExpr = fold257 del fold
modified:jinja2/runtime.py+30 added-3 removed
54 unmodified lines
55 # this is used for includes for example but otherwise, if the globals56 # are a template context, this template is participating in a template57 # inheritance chain and we have to copy the blocks over.58 if not standalone and isinstance(globals, TemplateContext):59 for name, parent_blocks in globals.blocks.iteritems():60 self.blocks.setdefault(name, []).extend(parent_blocks)59 for name, parent_blocks in globals.blocks.iteritems():60 self.blocks.setdefault(name, []).extend(parent_blocks)6162 def super(self, block):63 """Render a parent block."""64 try:65 func = self.blocks[block][-2]66 except LookupError:67 return Undefined('super', extra='there is probably no parent '68 'block with this name')69 return SuperBlock(block, self, func)7071 def __setitem__(self, key, value):72 """If we set items to the dict we track the variables set so73 that includes can access the exported variables."""74 dict.__setitem__(self, key, value)
25 unmodified lines
100 self.filename101 )102103104class SuperBlock(object):105 """When called this renders a parent block."""106107 def __init__(self, name, context, render_func):108 self.name = name109 self._context = context110 self._render_func = render_func111112 def __call__(self):113 return TemplateData(u''.join(self._render_func(self._context)))114115 def __repr__(self):116 return '<%s %r>' % (117 self.__class__.__name__,118 self.name119 )120121122class IncludedTemplate(object):123 """Represents an included template."""124125 def __init__(self, environment, context, template):
156 unmodified lines
282 if extra is not None:283 self._undefined_hint += ' (' + extra + ')'284285 def fail(self, *args, **kwargs):259 raise TypeError(self._undefined_hint)286 raise NameError(self._undefined_hint)287 __getattr__ = __getitem__ = __add__ = __mul__ = __div__ = \288 __realdiv__ = __floordiv__ = __mod__ = __pos__ = __neg__ = \289 __call__ = fail290 del fail
13 unmodified lines