work on tha runtime
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 7a52df8 · Browse files · 10 files·+111 added−149 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+111 added−149 removed
- other:+111 added−149 removed
Provenance
- Commit
bcb7c53- Tree
03d2f29- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
7a52df8
10 files changed+111 added−149 removed
modified:jinja2/compiler.py+7 added-6 removed
28 unmodified lines29 }30 31 32 def generate(node, environment, filename, stream=None):33+ """Generate the python source for a node tree."""34 is_child = node.find(nodes.Extends) is not None35 generator = CodeGenerator(environment, is_child, filename, stream)36 generator.visit(node)37 if stream is None:303 unmodified lines341 for x in self.blocks), extra=1)342 343 def visit_Block(self, node, frame):344 """Call a block and register it for the template."""344- # if we know that we are a child template, there is no need to345- # check if we are one346- if self.has_known_extends and frame.toplevel:347- return345 if frame.toplevel:346+ # if we know that we are a child template, there is no need to347+ # check if we are one348+ if self.has_known_extends:349+ return350 self.writeline('if parent_root is None:')351 self.indent()351- self.writeline('for event in context.blocks[-1][%r](context):' % node.name)352+ self.writeline('for event in context.blocks[0][%r](context):' % node.name)353 self.indent()354 self.writeline('yield event')355 self.outdent(1 + frame.toplevel)356 26 unmodified lines383 self.outdent()384 385 self.writeline('parent_root = extends(', node, 1)386 self.visit(node.template, frame)386- self.write(', context)')387+ self.write(', context, environment)')388 389 # if this extends statement was in the root level we can take390 # advantage of that information and simplify the generated code391 # in the top level from this point onwards346 unmodified linesmodified:jinja2/environment.py+52 added-1 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.optimizer import optimize14+from jinja2.compiler import generate15 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE16 17 18 class Environment(object):11 unmodified lines30 variable_end_string='}}',31 comment_start_string='{#',32 comment_end_string='#}',33 trim_blocks=False,32- template_charset='utf-8'):34+ template_charset='utf-8',35+ loader=None):36 """Here the possible initialization parameters:37 38 ========================= ============================================39 `block_start_string` the string marking the begin of a block.9 unmodified lines49 `trim_blocks` If this is set to ``True`` the first newline50 after a block is removed (block, not51 variable tag!). Defaults to ``False``.52 `template_charset` the charset of the templates.53+ `loader` the loader which should be used.54 ========================= ============================================55 """56 57 # lexer / parser information16 unmodified lines74 # finalizaion is written where it can be avoided.75 if not hasattr(self, 'finalize'):76 self.finalize = unicode77 78+ # set the loader provided79+ self.loader = loader80+81 # create lexer82 self.lexer = Lexer(self)83 84 def parse(self, source, filename=None):12 unmodified lines97 98 The tuples are returned in the form ``(lineno, token, value)``.99 """100 return self.lexer.tokeniter(source, filename)101+102+ def compile(self, source, filename=None, raw=False):103+ """Compile a node or source."""104+ if isinstance(source, basestring):105+ source = self.parse(source, filename)106+ node = optimize(source, self)107+ source = generate(node, self)108+ if raw:109+ return source110+ if isinstance(filename, unicode):111+ filename = filename.encode('utf-8')112+ return compile(source, filename, 'exec')113+114+ def join_path(self, template, parent):115+ """Join a template with the parent. By default all the lookups are116+ relative to the loader root, but if the paths should be relative this117+ function can be used to calculate the real filename."""118+ return template119+120+ def get_template(self, name, parent=None):121+ """Load a template."""122+ if self.loader is None:123+ raise TypeError('no loader for this environment specified')124+ if parent is not None:125+ name = self.join_path(name, parent)126+ return self.loader.load(self, name)127+128+129+class Template(object):130+ """Represents a template."""131+132+ def __init__(self, environment, code):133+ namespace = {'environment': environment}134+ exec code in namespace135+ self.environment = environment136+ self.root_render_func = namespace['root']137+ self.blocks = namespace['blocks']138+139+ def render(self, *args, **kwargs):140+ return u''.join(self.stream(*args, **kwargs))141+142+ def stream(self, *args, **kwargs):143+ context = dict(*args, **kwargs)144+ return self.root_render_func(context)modified:jinja2/lexer.py-3 removed
19 unmodified lines20 from jinja2.exceptions import TemplateSyntaxError21 from weakref import WeakValueDictionary22 23 24-__all__ = ['Lexer', 'Failure', 'keywords']25-26-24 # cache for the lexers. Exists in order to be able to have multiple25 # environments with the same lexer26 _lexer_cache = WeakValueDictionary()27 474 unmodified linesmodified:jinja2/loaders.py+40 added-3 removed
1 # -*- coding: utf-8 -*-2 """3- jinja.loaders4- ~~~~~~~~~~~~~3+ jinja2.loaders4+ ~~~~~~~~~~~~~~5 6 Jinja loader classes.7 8- :copyright: 2007 by Armin Ronacher, Bryan McLemore.8+ :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from os import path12+from jinja2.exceptions import TemplateNotFound13+from jinja2.environment import Template14+15+16+class BaseLoader(object):17+18+ def get_source(self, environment, template):19+ raise TemplateNotFound()20+21+ def load(self, environment, template):22+ source, filename = self.get_source(environment, template)23+ code = environment.compile(source, filename)24+ return Template(environment, code)25+26+27+class FileSystemLoader(BaseLoader):28+29+ def __init__(self, path, encoding='utf-8'):30+ self.path = path31+ self.encoding = encoding32+33+ def get_source(self, environment, template):34+ pieces = []35+ for piece in template.split('/'):36+ if piece == '..':37+ raise TemplateNotFound()38+ elif piece != '.':39+ pieces.append(piece)40+ filename = path.join(self.path, *pieces)41+ if not path.isfile(filename):42+ raise TemplateNotFound(template)43+ f = file(filename)44+ try:45+ return f.read().decode(self.encoding)46+ finally:47+ f.close()modified:jinja2/optimizer.py+7 added-7 removed
22 unmodified lines23 from jinja2.visitor import NodeVisitor, NodeTransformer24 from jinja2.runtime import subscribe, LoopContext25 26 27+def optimize(node, environment, context_hint=None):28+ """The context hint can be used to perform an static optimization29+ based on the context given."""30+ optimizer = Optimizer(environment)31+ return optimizer.visit(node, ContextStack(context_hint))32+33+34 class ContextStack(object):35 """Simple compile time context implementation."""36 undefined = object()37 174 unmodified lines212 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \213 visit_Not = visit_Compare = visit_Subscript = visit_Call = \214 visit_Filter = visit_Test = fold215 del fold209-210-211-def optimize(node, environment, context_hint=None):212- """The context hint can be used to perform an static optimization213- based on the context given."""214- optimizer = Optimizer(environment)215- return optimizer.visit(node, ContextStack(context_hint))modified:jinja2/parser.py-2 removed
10 unmodified lines11 from jinja2 import nodes12 from jinja2.exceptions import TemplateSyntaxError13 14 15-__all__ = ['Parser']16-15 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',16 'macro', 'include'])17 _compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])18 _statement_end_tokens = set(['elif', 'else', 'endblock', 'endfilter',637 unmodified linesmodified:jinja2/runtime.py+5 added-2 removed
16 unmodified lines17 __all__ = ['extends', 'subscribe', 'LoopContext', 'StaticLoopContext',18 'TemplateContext', 'Macro', 'Undefined']19 20 21-def extends(template, context):21+def extends(template_name, context, environment):22 """This loads a template (and evaluates it) and replaces the blocks."""23- context.stream_muted = True23+ template = environment.get_template(template_name, context.filename)24+ for name, block in template.blocks.iteritems():25+ context.blocks.setdefault(name, []).append(block)26+ return template.root_render_func27 28 29 def subscribe(obj, argument):30 """Get an item or attribute of an object."""194 unmodified linesdeleted:jdebug.py-70 removed
1-# -*- coding: utf-8 -*-2-"""3- jdebug4- ~~~~~~5-6- Helper module to simplify jinja debugging. Use7-8- :copyright: 2006 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import sys13-import gc14-from jinja import Environment15-from jinja.parser import Parser16-from jinja.lexer import Lexer17-from jinja.translators.python import PythonTranslator18-19-20-__all__ = ['e', 't', 'p', 'l', 'm']21-22-23-_global_frame = sys._getframe()24-e = Environment()25-t = e.from_string26-27-28-def p(x=None, f=None):29- if x is None and f is not None:30- x = e.loader.get_source(f)31- print PythonTranslator(e, Parser(e, x, f).parse(), None).translate()32-33-def l(x):34- for item in e.lexer.tokenize(x):35- print '%5s %-20s %r' % (item.lineno,36- item.type,37- item.value)38-39-class MemoryGuard(object):40-41- def __init__(self):42- self.guarded_objects = {}43- self.clear = self.guarded_objects.clear44-45- def freeze(self):46- self.clear()47- for obj in gc.get_objects():48- self.guarded_objects[id(obj)] = True49-50- def get_delta(self):51- frm = sys._getframe()52- result = []53- for obj in gc.get_objects():54- if id(obj) not in self.guarded_objects and \55- obj is not frm and obj is not result:56- result.append(obj)57- return result58-59-60-m = MemoryGuard()61-62-63-if __name__ == '__main__':64- if len(sys.argv) > 1:65- from jinja import FileSystemLoader66- e.loader = FileSystemLoader(sys.argv[1])67- if len(sys.argv) > 2:68- p(f=sys.argv[2])69- else:70- p(sys.stdin.read())deleted:test_optimizer.py-34 removed
1-from jinja2 import Environment2-from jinja2.compiler import generate3-from jinja2.optimizer import optimize4-5-6-env = Environment()7-forums = [8- {'id': 1, 'name': u'Example'},9- {'id': 2, 'name': u'Foobar'},10- {'id': 3, 'name': u'<42>'}11-]12-ast = env.parse("""13- Hi {{ "<blub>"|e }},14- how are you?15-16- {% for forum in forums %}17- {{ readstatus(forum.id) }} {{ forum.id|e }} {{ forum.name|e }}18- {% endfor %}19-20- {% navigation = [('#foo', 'Foo'), ('#bar', 'Bar'), ('#baz', 42 * 2 + 23)] %}21- <ul>22- {% for key, value in navigation %}23- <li>{{ loop.index }}: <a href="{{ key[1:].upper()|e }}">{{ value|e }}</a></li>24- {% endfor %}25- </ul>26-""")27-print ast28-print29-print generate(ast, env, "foo.html")30-print31-ast = optimize(ast, env, context_hint={'forums': forums})32-print ast33-print34-print generate(ast, env, "foo.html")deleted:test.py-21 removed
1-import sys2-from jinja2 import Environment3-from jinja2.compiler import generate4-5-6-env = Environment()7-ast = env.parse("""8-{% extends master_layout or "foo.html" %}9-10-{% baz = [1, 2, 3, 4] %}11-{% macro foo() %}12- blah13-{% endmacro %}14-{% blah = 42 %}15-16-{% block body %}17- Das ist ein Test18-{% endblock %}19-""")20-source = generate(ast, env, "foo.html")21-print source