Skip to content
Myr

[svn] checked in todays jinja changes

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 303a7e4 · Browse files · 8 files+179 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+179 added−62 removed

  • other:+179 added−62 removed

8 files+179 added−62 removed

modified:jinja/translators/python.py+60 added-26 removed
29 unmodified lines
30 """31 Represents a finished template.32 """3334 def __init__(self, environment, generate_func):34 def __init__(self, environment, code):35 self.environment = environment36 self.generate_func = generate_func36 self.code = code37 self.generate_func = None3839 def dump(self, filename):40 """Dump the template into python bytecode."""41 from marshal import dumps42 return dumps(self.code)4344 def load(environment, data):45 """Load the template from python bytecode."""46 from marshal import loads47 code = loads(data)48 return Template(environment, code)49 load = staticmethod(load)5051 def render(self, *args, **kwargs):39 """40 Render a template.41 """52 """Render a template."""53 if self.generate_func is None:54 ns = {}55 exec self.code in ns56 self.generate_func = ns['generate']57 result = []58 ctx = Context(self.environment, *args, **kwargs)59 self.generate_func(ctx, result.append)60 return u''.join(result)
67 unmodified lines
128 # -- public methods129130 def process(environment, node):131 translator = PythonTranslator(environment, node)117 source = translator.translate()118 ns = {}119 exec source in ns120 return Template(environment, ns['generate'])132 return Template(environment,133 compile(translator.translate(), node.filename, 'exec'))134 process = staticmethod(process)135136 # -- private methods137
23 unmodified lines
161 """162 Handle the overall template node. This node is the first node and ensures163 that we get the bootstrapping code. It also knows about inheritance164 information. It only occours as outer node, never in the tree itself.152153 Nevertheless we call indent here to simplify futur changes.165 """166 # if there is a parent template we parse the parent template and167 # update the blocks there. Once this is done we drop the current168 # template in favor of the new one. Do that until we found the
5 unmodified lines
174 if block.name in node.blocks:175 block.replace(node.blocks[block.name])176 node = tmpl177167 lines = [self.indent(178 lines = [179 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n\n'180 'def generate(context, write):\n'181 ' # BOOTSTRAPPING CODE\n'182 ' environment = context.environment\n'
2 unmodified lines
185 ' apply_filters = environment.apply_filters\n'186 ' call_function = environment.call_function\n'187 ' call_function_simple = environment.call_function_simple\n'188 ' finish_var = environment.finish_var\n'178 ' write_var = lambda x: write(finish_var(x))\n'179 ' filtercache = {}\n\n'189 ' write_var = lambda x: write(finish_var(x))\n\n'190 ' # TEMPLATE CODE'181 )]191 ]192 self.indention += 1193 lines.append(self.handle_node_list(node))194 self.indention -= 1195196 return '\n'.join(lines)197198 def handle_template_text(self, node):
92 unmodified lines
291292 write('if not %r in context.current:' % name)293 self.indention += 1294 if node.seq.__class__ in (ast.Tuple, ast.List):284 write('context.current[%r] = CycleContext([%s])' % (295 write('context.current[%r] = CycleContext(%s)' % (296 name,286 ', '.join([self.handle_node(n) for n in node.seq.nodes])297 _to_tuple([self.handle_node(n) for n in node.seq.nodes])298 ))299 hardcoded = True300 else:301 write('context.current[%r] = CycleContext()' % name)
78 unmodified lines
380 """381 # the semantic for the is operator is different.382 # for jinja the is operator performs tests and must383 # be the only operator373 if node.ops[0][0] == 'is':384 if node.ops[0][0] in ('is', 'is not'):385 if len(node.ops) > 1:386 raise TemplateSyntaxError('is operator must not be chained',387 node.lineno)377 elif node.ops[0][1].__class__ is not ast.Name:378 raise TemplateSyntaxError('is operator requires a test name',388 elif node.ops[0][1].__class__ is ast.Name:389 args = []390 name = node.ops[0][1].name391 elif node.ops[0][1].__class__ is ast.CallFunc:392 n = node.ops[0][1]393 if n.node.__class__ is not ast.Name:394 raise TemplateSyntaxError('invalid test. test must '395 'be a hardcoded function name '396 'from the test namespace',397 n.lineno)398 name = n.node.name399 args = []400 for arg in n.args:401 if arg.__class__ is ast.Keyword:402 raise TemplateSyntaxError('keyword arguments for '403 'tests are not supported.',404 n.lineno)405 args.append(self.handle_node(arg))406 if n.star_args is not None or n.dstar_args is not None:407 raise TemplateSynaxError('*args / **kwargs is not supported '408 'for tests', n.lineno)409 else:410 raise TemplateSyntaxError('is operator requires a test name'411 ' as operand', node.lineno)380 return 'perform_test(context, %r, %s)' % (381 node.ops[0][1].name,382 self.handle_node(node.expr)383 )412 return 'perform_test(context, %r, %s, %s, %s)' % (413 name,414 _to_tuple(args),415 self.handle_node(node.expr),416 node.ops[0][0] == 'is not'417 )418419 # normal operators420 buf = []421 buf.append(self.handle_node(node.expr))422 for op, n in node.ops:389 if op == 'is':423 if op in ('is', 'is not'):424 raise TemplateSyntaxError('is operator must not be chained',425 node.lineno)426 buf.append(op)427 buf.append(self.handle_node(n))
70 unmodified lines
498 raise TemplateSyntaxError('invalid filter. filter must be a '499 'hardcoded function name from the '500 'filter namespace',501 n.lineno)468 return 'apply_filters(%s, filtercache, context, %s)' % (502 return 'apply_filters(%s, context, %s)' % (503 self.handle_node(node.nodes[0]),504 _to_tuple(filters)505 )506
168 unmodified lines
modified:jinja/datastructure.py+30 added-4 removed
15 unmodified lines
16except NameError:17 def _reversed(c):18 return c[::-1]1920# sets21try:22 set23except NameError:24 from sets import Set as set252627class UndefinedType(object):28 """29 An object that does not exist.30 """
51 unmodified lines
82 def __call__(self, context, name):83 return self.factory(context, name)848586class Markup(unicode):87 """88 Mark a string as safe for XML. If the environment uses the89 auto_escape option values marked as `Markup` aren't escaped.90 """919293safe_types = set([Markup, int, long, float])949596class Context(object):97 """98 Dict like object.99 """100101 def __init__(self, _environment_, *args, **kwargs):102 self.environment = _environment_87 self._stack = [self.environment.globals, dict(*args, **kwargs), {}]88 self.globals, _, self.current = self._stack103 self._stack = [self.environment.globals, dict(*args, **kwargs), {}, {}]104 self.globals, self.initial, self.current = self._stack105106 # cache object used for filters and tests107 self.cache = {}108109 def pop(self):110 if len(self._stack) <= 2:111 raise ValueError('cannot pop initial layer')112 rv = self._stack.pop()
21 unmodified lines
134 for d in _reversed(self._stack):135 if name in d:136 rv = d[name]137 if isinstance(rv, Deferred):119 d[name] = rv = rv(self, name)138 rv = rv(self, name)139 # never tough the globals!140 if d is self.globals:141 self.initial[name] = rv142 else:143 d[name] = rv144 return rv145 return Undefined146147 def __setitem__(self, name, value):
17 unmodified lines
165 Used by `Environment.iterate`.166 """167168 jinja_allowed_attributes = ['index', 'index0', 'length', 'parent',145 'even', 'odd']169 'even', 'odd', 'revindex0', 'revindex']170171 def __init__(self, seq, parent, loop_function):172 self.loop_function = loop_function173 self.parent = parent
13 unmodified lines
187188 iterated = property(lambda s: s._stack[-1]['index'] > -1)189 index0 = property(lambda s: s._stack[-1]['index'])190 index = property(lambda s: s._stack[-1]['index'] + 1)191 revindex0 = property(lambda s: s._stack[-1]['length'] - s._stack[-1]['index'] - 1)192 revindex = property(lambda s: s._stack[-1]['length'] - s._stack[-1]['index'])193 length = property(lambda s: s._stack[-1]['length'])194 even = property(lambda s: s._stack[-1]['index'] % 2 == 0)195 odd = property(lambda s: s._stack[-1]['index'] % 2 == 1)196
96 unmodified lines
modified:jinja/environment.py+33 added-14 removed
6 unmodified lines
78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined16from jinja.utils import escape15from jinja.exceptions import FilterNotFound, TestNotFound17from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE192021class Environment(object):
7 unmodified lines
29 variable_start_string='{{',30 variable_end_string='}}',31 comment_start_string='{#',32 comment_end_string='#}',33 trim_blocks=False,34 auto_escape=False,35 template_charset='utf-8',36 charset='utf-8',37 namespace=None,38 loader=None,
6 unmodified lines
45 self.variable_start_string = variable_start_string46 self.variable_end_string = variable_end_string47 self.comment_start_string = comment_start_string48 self.comment_end_string = comment_end_string49 self.trim_blocks = trim_blocks5051 # other stuff52 self.template_charset = template_charset53 self.charset = charset54 self.loader = loader55 self.filters = filters is None and DEFAULT_FILTERS.copy() or filters56 self.tests = tests is None and DEFAULT_TESTS.copy() or tests57 self.auto_escape = auto_escape5859 # global namespace60 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \61 or namespace
18 unmodified lines
80 from jinja.parser import Parser81 from jinja.translators.python import PythonTranslator82 return PythonTranslator.process(self, Parser(self, source).parse())8384 def get_template(self, filename):85 """Load a template from a filename. Only works86 if a proper loader is set."""87 return self._loader.load(filename)8889 def to_unicode(self, value):90 """91 Convert a value to unicode with the rules defined on the environment.92 """
4 unmodified lines
97 return unicode(value)98 except UnicodeError:99 return str(value).decode(self.charset, 'ignore')10090 def apply_filters(self, value, filtercache, context, filters):101 def apply_filters(self, value, context, filters):102 """103 Apply a list of filters on the variable.104 """105 for key in filters:95 if key in filtercache:96 func = filtercache[key]106 if key in context.cache:107 func = context.cache[key]108 else:109 filtername, args = key110 if filtername not in self.filters:111 raise FilterNotFound(filtername)101 filtercache[key] = func = self.filters[filtername](*args)112 context.cache[key] = func = self.filters[filtername](*args)113 value = func(self, context, value)114 return value115105 def perform_test(self, context, testname, value):116 def perform_test(self, context, testname, args, value, invert):117 """118 Perform a test on a variable.119 """120 key = (testname, args)121 if key in context.cache:122 func = context.cache[key]123 else:109 if testname not in self.tests:110 raise TestNotFound(testname)111 return bool(self.tests[testname](self, context, value))124 if testname not in self.tests:125 raise TestNotFound(testname)126 context.cache[key] = func = self.tests[testname](*args)127 rv = func(self, context, value)128 if invert:129 return not rv130 return bool(rv)131132 def get_attribute(self, obj, name):133 """134 Get the attribute name from obj.
4 unmodified lines
139 rv = getattr(obj, name)140 r = getattr(obj, 'jinja_allowed_attributes', None)141 if r is not None:142 if name not in r:124 raise AttributeError()143 raise SecurityException('unsafe attributed %r accessed' % name)144 return rv145 return Undefined146147 def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):
20 unmodified lines
168 def finish_var(self, value):169 """170 As long as no write_var function is passed to the template171 evaluator the source generated by the python translator will153 call this function for all variables. You can use this to154 enable output escaping etc or just ensure that None and155 Undefined values are rendered as empty strings.172 call this function for all variables.173 """157 if value is None or value is Undefined:174 if value is Undefined:175 return u''176 elif self.auto_escape:177 return escape(value, True)178 return unicode(value)
modified:jinja/exceptions.py+6 added
12 unmodified lines
13class TemplateError(RuntimeError):14 pass151617class SecurityException(TemplateError):18 """19 Raise if the template designer tried to do something dangerous.20 """212223class FilterNotFound(KeyError, TemplateError):24 """25 Raised if a filter does not exist.26 """
42 unmodified lines
modified:jinja/filters.py+2 added-4 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from random import choice12from urllib import urlencode, quote13from jinja.utils import escape141516try:17 _reversed = reversed
65 unmodified lines
8384 XML escape &, <, and > in a string of data. If attribute is85 True it also converts ``"`` to ``&quot;``86 """86 s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")87 if attribute:88 s = s.replace('"', "&quot;")89 return s87 return escape(s, attribute)88do_escape = stringfilter(do_escape)899091def do_addslashes(s):
238 unmodified lines
modified:jinja/lexer.py+2 added-8 removed
79 unmodified lines
80 'root': [81 (c('(.*?)(?:%s)' % '|'.join([82 '(?P<%s_begin>%s)' % (n, e(r)) for n, r in root_tag_rules83 ])), ('data', '#bygroup'), '#bygroup'),84 #(c('(.*?)(?:(?P<comment_begin>' +85 # e(environment.comment_start_string) +86 # ')|(?P<block_begin>' +87 # e(environment.block_start_string) +88 # ')|(?P<variable_begin>' +89 # e(environment.variable_start_string) +90 # '))'), ('data', '#bygroup'), '#bygroup'),84 (c('.+'), 'data', None)85 ],86 'comment_begin': [87 (c(r'(.*?)(%s)' % e(environment.comment_end_string)),88 ('comment', 'comment_end'), '#pop'),89 (c('(.)'), (Failure('Missing end of comment tag'),), None)90 ],91 'block_begin': [99 (c(e(environment.block_end_string)), 'block_end', '#pop')92 (c(e(environment.block_end_string) +93 (environment.trim_blocks and '\\n?' or '')), 'block_end', '#pop')94 ] + tag_rules,95 'variable_begin': [96 (c(e(environment.variable_end_string)), 'variable_end',97 '#pop')
112 unmodified lines
modified:jinja/loaders.py+12 added-6 removed
30 unmodified lines
3132 def __init__(self, environment, loader):33 self.environment = environment34 self.loader = loader35 if self.loader is None:36 self.get_source = self.parse = self.load = self._loader_missing37 self.available = False38 else:39 self.available = True4041 def get_source(self, name, parent=None):37 """38 Retrieve the sourcecode of a template.39 """42 """Retrieve the sourcecode of a template."""43 # just ascii chars are allowed as template names44 name = str(name)45 return self.loader.get_source(self.environment, name, parent)4647 def parse(self, name, parent=None):45 """46 Retreive a template and parse it.47 """48 """Retreive a template and parse it."""49 # just ascii chars are allowed as template names50 name = str(name)51 return self.loader.parse(self.environment, name, parent)52
6 unmodified lines
59 # just ascii chars are allowed as template names60 name = str(name)61 return self.loader.load(self.environment, name, translator)6263 def _loader_missing(self, *args, **kwargs):64 """Helper method that overrides all other methods if no65 loader is defined."""66 raise RuntimeError('no loader defined')676869class FileSystemLoader(object):70 """71 Loads templates from the filesystem::72
36 unmodified lines
added:jinja/utils.py+34 added
1# -*- coding: utf-8 -*-2"""3 jinja.utils4 ~~~~~~~~~~~56 Utility functions.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.datastructure import safe_types131415_escape_pairs = {16 '&': '&amp;',17 '<': '&lt;',18 '>': '&gt;',19 '"': '&quot;'20}2122_escape_res = (23 re.compile('(&|<|>|")'),24 re.compile('(&|<|>)')25)2627def escape(x, attribute=False):28 """29 Escape an object x which is converted to unicode first.30 """31 if type(x) in safe_types:32 return x33 return _escape_res[not attribute].sub(lambda m: _escape_pairs[m.group()],34 unicode(x))