Skip to content
Myr

fixed one bug with blocks, one to go

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 d436e98 · Browse files · 8 files+121 added−62 removed
This commit

State

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

Diff stats

8 files+121 added−62 removed

  • other:+121 added−62 removed

8 files+121 added−62 removed

modified:jinja2/compiler.py+38 added-9 removed
255 unmodified lines
256 def visit_Template(self, node, frame=None):257 assert frame is None, 'no root frame allowed'258 self.writeline('from jinja2.runtime import *')259 self.writeline('filename = %r' % self.filename)260 self.writeline('template_context = TemplateContext(global_context, '261 'filename)')260261 # find all blocks262 for block in node.find_all(nodes.Block):263 if block.name in self.blocks:264 raise TemplateAssertionError('block %r defined twice' %265 block.name, block.lineno,266 self.filename)267 self.blocks[block.name] = block268269 # generate the root render function.264 self.writeline('def root(context=template_context):', extra=1)270 self.writeline('def root(context):', extra=1)271 self.indent()272 self.writeline('parent_root = None')273 self.outdent()274 frame = Frame()
15 unmodified lines
290 for name, block in self.blocks.iteritems():291 block_frame = Frame()292 block_frame.inspect(block.body)293 block_frame.block = name294 print block_frame.identifiers.__dict__295 self.writeline('def block_%s(context):' % name, block, 1)296 self.pull_locals(block_frame)297 self.blockvisit(block.body, block_frame, True)298299 def visit_Block(self, node, frame):300 """Call a block and register it for the template."""294 if node.name in self.blocks:295 raise TemplateAssertionError("the block '%s' was already defined" %296 node.name, node.lineno,297 self.filename)298 self.blocks[node.name] = node301 self.writeline('for event in block_%s(context):' % node.name)302 self.indent()303 self.writeline('yield event')304 self.outdent()
125 unmodified lines
430431 def visit_Output(self, node, frame):432 self.newline(node)433434 if self.environment.finalize is unicode:435 finalizer = 'unicode'436 else:437 finalizer = 'context.finalize'438439 # try to evaluate as many chunks as possible into a static440 # string at compile time.441 body = []442 for child in node.nodes:
13 unmodified lines
456 if isinstance(item, list):457 self.writeline('yield %s' % repr(u''.join(item)))458 else:459 self.newline(item)453 self.write('yield unicode(')460 self.write('yield %s(' % finalizer)461 self.visit(item, frame)462 self.write(')')463464 # otherwise we create a format string as this is faster in that case
10 unmodified lines
475 idx = -1476 for idx, argument in enumerate(arguments):477 if idx:478 self.write(', ')479 if finalizer != 'unicode':480 self.write('(')481 self.visit(argument, frame)482 if finalizer != 'unicode':483 self.write(')')484 self.write(idx == 0 and ',)' or ')')485486 def visit_Assign(self, node, frame):487 self.newline(node)
36 unmodified lines
524 self.write(', ')525 self.visit(item, frame)526 self.write(idx == 0 and ',)' or ')')527528 def visit_List(self, node, frame):529 self.write('[')530 for idx, item in enumerate(node.items):531 if idx:532 self.write(', ')533 self.visit(item, frame)534 self.write(']')535536 def visit_Dict(self, node, frame):537 self.write('{')538 for idx, item in enumerate(node.items):539 if idx:540 self.write(', ')541 self.visit(item.key, frame)542 self.write(': ')543 self.visit(item.value, frame)544 self.write('}')545546 def binop(operator):547 def visitor(self, node, frame):548 self.write('(')549 self.visit(node.left, frame)
96 unmodified lines
modified:jinja2/environment.py+10 added-14 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja2.lexer import Lexer12from jinja2.parser import Parser13from jinja2.runtime import Undefined13from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE141516class Environment(object):18 """19 The Jinja environment.17 """The Jinja environment.1819 The core component of Jinja is the `Environment`. It contains20 important shared variables like configuration, filters, tests,21 globals and others.
7 unmodified lines
29 comment_start_string='{#',30 comment_end_string='#}',31 trim_blocks=False,32 template_charset='utf-8'):35 """36 Here the possible initialization parameters:33 """Here the possible initialization parameters:3435 ========================= ============================================36 `block_start_string` the string marking the begin of a block.37 this defaults to ``'{%'``.
26 unmodified lines
64 self.filters = DEFAULT_FILTERS.copy()65 self.tests = DEFAULT_TESTS.copy()66 self.globals = DEFAULT_NAMESPACE.copy()6771 # the factory that creates the undefined object72 self.undefined_factory = Undefined68 # if no finalize function/method exists we default to unicode. The69 # compiler check if the finalize attribute *is* unicode, if yes no70 # finalizaion is written where it can be avoided.71 if not hasattr(self, 'finalize'):72 self.finalize = unicode7374 # create lexer75 self.lexer = Lexer(self)7677 def parse(self, source, filename=None):78 """79 Parse the sourcecode and return the abstract syntax tree. This tree80 of nodes is used by the `translators`_ to convert the template into78 """Parse the sourcecode and return the abstract syntax tree. This tree79 of nodes is used by the compiler to convert the template into80 executable source- or bytecode.8283 .. _translators: translators.txt81 """82 parser = Parser(self, source, filename)83 return parser.parse()8485 def lex(self, source, filename=None):89 """90 Lex the given sourcecode and return a generator that yields tokens.86 """Lex the given sourcecode and return a generator that yields tokens.87 The stream returned is not usable for Jinja but can be used if88 Jinja templates should be processed by other tools (for example89 syntax highlighting etc)90
3 unmodified lines
modified:jinja2/filters.py+6 added-16 removed
13 unmodified lines
14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja.utils import escape18from jinja2.utils import escape192021_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')222324def contextfilter(f):25 """26 Decorator for marking context dependent filters. The current context25 """Decorator for marking context dependent filters. The current context26 argument will be passed as first argument.27 """28 f.contextfilter = True29 return f
28 unmodified lines
58 return s.replace(old, new, count)596061def do_upper(s):63 """64 Convert a value to uppercase.65 """66 return s.upper()62 """Convert a value to uppercase."""63 return unicode(s).upper()646566def do_lower(s):70 """71 Convert a value to lowercase.72 """73 return s.lower()67 """Convert a value to lowercase."""68 return unicode(s).lower()697071def do_escape(s, attribute=False):72 """
3 unmodified lines
76 was configured with disabled `auto_escape`.7778 This method will have no effect it the value is already escaped.79 """85 # XXX: Does this still exists?86 #if isinstance(s, TemplateData):87 # return s88 if hasattr(s, '__html__'):89 return s.__html__()80 return escape(unicode(s), attribute)818283def do_xmlattr(d, autospace=False):
820 unmodified lines
modified:jinja2/optimizer.py+29 added-1 removed
24 unmodified lines
252627class ContextStack(object):28 """Simple compile time context implementation."""29 undefined = object()3031 def __init__(self, initial=None):32 self.stack = [{}]33 if initial is not None:
10 unmodified lines
44 return self[key]45 except KeyError:46 return default4748 def undef(self, name):49 if name in self:50 self[name] = self.undefined5152 def __contains__(self, key):53 try:54 self[key]55 except KeyError:56 return False57 return True5859 def __getitem__(self, key):60 for level in reversed(self.stack):61 if key in level:50 return level[key]62 rv = level[key]63 if rv is self.undefined:64 raise KeyError(key)65 return rv66 raise KeyError(key)6768 def __setitem__(self, key, value):69 self.stack[-1][key] = value
10 unmodified lines
8081 def visit_Block(self, node, context):82 return self.generic_visit(node, context.blank())8384 def visit_Macro(self, node, context):85 context.push()86 try:87 return self.generic_visit(node, context)88 finally:89 context.pop()9091 def visit_For(self, node, context):92 """Loop unrolling for iterable constant values."""93 try:94 iterable = self.visit(node.iter, context).as_const()95 # we only unroll them if they have a length and are iterable96 iter(iterable)97 len(iterable)98 # we also don't want unrolling if macros are defined in it99 if node.find(nodes.Macro) is not None:100 raise TypeError()101 except (nodes.Impossible, TypeError):102 return self.generic_visit(node, context)103104 parent = context.get('loop')
43 unmodified lines
148 return node.else_149150 def visit_Name(self, node, context):151 if node.ctx != 'load':152 # something overwrote the variable, we can no longer use153 # the constant from the context154 context.undef(node.name)155 return node156 try:157 return nodes.Const.from_untrusted(context[node.name],158 lineno=node.lineno,
57 unmodified lines
modified:jinja2/parser.py+4 added-2 removed
53 unmodified lines
54 token_type = self.stream.current.type55 if token_type in _statement_keywords:56 return getattr(self, 'parse_' + token_type)()57 elif token_type is 'call':58 self.stream.next()58 return self.parse_call_block()59 lineno = self.stream.current60 expr = self.parse_tuple()61 if self.stream.current.type == 'assign':
115 unmodified lines
177 return node178179 def parse_call_block(self):180 node = nodes.CallBlock(lineno=self.stream.expect('call').lineno)182 node.call = self.parse_call()181 node.call = self.parse_expression()182 if not isinstance(node.call, nodes.Call):183 raise TemplateSyntaxError('expected call', node.lineno,184 self.filename)185 node.body = self.parse_statements(('endcall',), drop_needle=True)186 return node187188 def parse_macro(self):
469 unmodified lines
modified:jinja2/runtime.py+11 added-3 removed
31 unmodified lines
32 except LookupError:33 return Undefined(obj, argument)343536class TemplateData(unicode):37 """Marks data as "coming from the template". This is used to let the38 system know that this data is already processed if a finalization is39 used."""4041 def __html__(self):42 return self434445class TemplateContext(dict):37 """38 Holds the variables of the local template or of the global one. It's46 """Holds the variables of the local template or of the global one. It's47 not save to use this class outside of the compiled code. For example48 update and other methods will not work as they seem (they don't update49 the exported variables for example).50 """
133 unmodified lines
184 value = Undefined(name)185 arguments['l_' + name] = value186 if self.catch_all:187 arguments['l_arguments'] = kwargs180 return u''.join(self.func(**arguments))188 return TemplateData(u''.join(self.func(**arguments)))189190191class Undefined(object):192 """The object for undefined values."""
28 unmodified lines
modified:jinja2/utils.py+13 added
6 unmodified lines
78 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213def escape(obj, attribute=False):14 """HTML escape an object."""15 if hasattr(obj, '__html__'):16 return obj.__html__()17 s = unicode(obj) \18 .replace('&', '&amp;') \19 .replace('>', '&gt;') \20 .replace('<', '&lt;')21 if attribute:22 s = s.replace('"', '&quot;')23 return s
modified:test.py+10 added-17 removed
3 unmodified lines
456env = Environment()7ast = env.parse("""8{% block body %}9 {% b = 23 %}10 {% macro foo(a) %}[{{ a }}|{{ b }}|{{ c }}]{% endmacro %}11 {% for item in seq %}12 {{ foo(item) }}13 {%- endfor %}8hallo9{% block root %}10 inhalt11 {% x = 3 %}12 {% block inner %}13 {% x = x + 2 %}14 {{ x }}15 {% endblock %}16 {{ x }}17{% endblock %}18ende19""")16print ast17print20source = generate(ast, env, "foo.html")21print source20print2122# execute the template23code = compile(source, 'jinja://foo.html', 'exec')24context = {'seq': range(5), 'c': 'foobar'}25namespace = {'global_context': context}26exec code in namespace27for event in namespace['root'](context):28 sys.stdout.write(event)