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
Provenance
- Commit
8edbe49- Tree
41f7ead- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d436e98
8 files changed+121 added−62 removed
modified:jinja2/compiler.py+38 added-9 removed
255 unmodified lines256 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)')260 261+ # 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] = block268+269 # 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 lines290 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)298 299 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 lines430 431 def visit_Output(self, node, frame):432 self.newline(node)433 434+ if self.environment.finalize is unicode:435+ finalizer = 'unicode'436+ else:437+ finalizer = 'context.finalize'438+439 # 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 lines456 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(')')463 464 # otherwise we create a format string as this is faster in that case10 unmodified lines475 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 ')')485 486 def visit_Assign(self, node, frame):487 self.newline(node)36 unmodified lines524 self.write(', ')525 self.visit(item, frame)526 self.write(idx == 0 and ',)' or ')')527 528+ 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(']')535+536+ 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('}')545+546 def binop(operator):547 def visitor(self, node, frame):548 self.write('(')549 self.visit(node.left, frame)96 unmodified linesmodified:jinja2/environment.py+10 added-14 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja2.lexer import Lexer12 from jinja2.parser import Parser13-from jinja2.runtime import Undefined13 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE14 15 16 class Environment(object):18- """19- The Jinja environment.17+ """The Jinja environment.18 19 The core component of Jinja is the `Environment`. It contains20 important shared variables like configuration, filters, tests,21 globals and others.7 unmodified lines29 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:34 35 ========================= ============================================36 `block_start_string` the string marking the begin of a block.37 this defaults to ``'{%'``.26 unmodified lines64 self.filters = DEFAULT_FILTERS.copy()65 self.tests = DEFAULT_TESTS.copy()66 self.globals = DEFAULT_NAMESPACE.copy()67 71- # 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 = unicode73 74 # create lexer75 self.lexer = Lexer(self)76 77 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.82-83- .. _translators: translators.txt81 """82 parser = Parser(self, source, filename)83 return parser.parse()84 85 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 linesmodified:jinja2/filters.py+6 added-16 removed
13 unmodified lines14 from operator import itemgetter15 except ImportError:16 itemgetter = lambda a: lambda b: b[a]17 from urllib import urlencode, quote18-from jinja.utils import escape18+from jinja2.utils import escape19 20 21 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')22 23 24 def 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 f28 unmodified lines58 return s.replace(old, new, count)59 60 61 def 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()64 65 66 def 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()69 70 71 def do_escape(s, attribute=False):72 """3 unmodified lines76 was configured with disabled `auto_escape`.77 78 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)81 82 83 def do_xmlattr(d, autospace=False):820 unmodified linesmodified:jinja2/optimizer.py+29 added-1 removed
24 unmodified lines25 26 27 class ContextStack(object):28 """Simple compile time context implementation."""29+ undefined = object()30 31 def __init__(self, initial=None):32 self.stack = [{}]33 if initial is not None:10 unmodified lines44 return self[key]45 except KeyError:46 return default47 48+ def undef(self, name):49+ if name in self:50+ self[name] = self.undefined51+52+ def __contains__(self, key):53+ try:54+ self[key]55+ except KeyError:56+ return False57+ return True58+59 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)67 68 def __setitem__(self, key, value):69 self.stack[-1][key] = value10 unmodified lines80 81 def visit_Block(self, node, context):82 return self.generic_visit(node, context.blank())83 84+ def visit_Macro(self, node, context):85+ context.push()86+ try:87+ return self.generic_visit(node, context)88+ finally:89+ context.pop()90+91 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)103 104 parent = context.get('loop')43 unmodified lines148 return node.else_149 150 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 linesmodified:jinja2/parser.py+4 added-2 removed
53 unmodified lines54 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 lines177 return node178 179 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 node187 188 def parse_macro(self):469 unmodified linesmodified:jinja2/runtime.py+11 added-3 removed
31 unmodified lines32 except LookupError:33 return Undefined(obj, argument)34 35 36+class 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."""40+41+ def __html__(self):42+ return self43+44+45 class 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 lines184 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)))189 190 191 class Undefined(object):192 """The object for undefined values."""28 unmodified linesmodified:jinja2/utils.py+13 added
6 unmodified lines7 8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+12+13+def escape(obj, attribute=False):14+ """HTML escape an object."""15+ if hasattr(obj, '__html__'):16+ return obj.__html__()17+ s = unicode(obj) \18+ .replace('&', '&') \19+ .replace('>', '>') \20+ .replace('<', '<')21+ if attribute:22+ s = s.replace('"', '"')23+ return smodified:test.py+10 added-17 removed
3 unmodified lines4 5 6 env = Environment()7 ast = 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 %}8+hallo9+{% block root %}10+ inhalt11+ {% x = 3 %}12+ {% block inner %}13+ {% x = x + 2 %}14+ {{ x }}15+ {% endblock %}16+ {{ x }}17 {% endblock %}18+ende19 """)16-print ast17-print20 source = generate(ast, env, "foo.html")21 print source20-print21-22-# execute the template23-code = compile(source, 'jinja://foo.html', 'exec')24-context = {'seq': range(5), 'c': 'foobar'}25-namespace = {'global_context': context}26-exec code in namespace27-for event in namespace['root'](context):28- sys.stdout.write(event)