Skip to content
Myr

[svn] added new jinja trunk

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 · the first commit · Browse files · 18 files+1824 added−0 removed
This commit

State

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

Diff stats

18 files+1824 added−0 removed

  • tests:+168 added−0 removed
  • other:+1656 added−0 removed

18 files+1824 added−0 removed

added:jinja/translators/__init__.py+11 added
1# -*- coding: utf-8 -*-2"""3 jinja.translators4 ~~~~~~~~~~~~~~~~~56 The submodules of this module provide translators for the jinja ast7 which basically just is the python ast with a few more nodes.89 :copyright: 2006 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""
added:jinja/translators/python.py+351 added
1# -*- coding: utf-8 -*-2"""3 jinja.translators.python4 ~~~~~~~~~~~~~~~~~~~~~~~~56 This module translates a jinja ast into python code.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from compiler import ast12from jinja import nodes131415class PythonTranslator(object):16 """17 Pass this translator a ast tree to get valid python code.18 """1920 def __init__(self, environment, node):21 self.environment = environment22 self.node = node23 self.indention = 024 self.last_pos = 02526 self.handlers = {27 # jinja nodes28 nodes.Text: self.handle_template_text,29 nodes.NodeList: self.handle_node_list,30 nodes.ForLoop: self.handle_for_loop,31 nodes.IfCondition: self.handle_if_condition,32 nodes.Print: self.handle_print,33 # used python nodes34 ast.Name: self.handle_name,35 ast.AssName: self.handle_name,36 ast.Compare: self.handle_compare,37 ast.Const: self.handle_const,38 ast.Subscript: self.handle_subscript,39 ast.Getattr: self.handle_getattr,40 ast.AssTuple: self.handle_ass_tuple,41 ast.Bitor: self.handle_bitor,42 ast.CallFunc: self.handle_call_func,43 ast.Add: self.handle_add,44 ast.Sub: self.handle_sub,45 ast.Div: self.handle_div,46 ast.Mul: self.handle_mul,47 ast.Mod: self.handle_mod,48 ast.UnarySub: self.handle_unary_sub,49 ast.Power: self.handle_power,50 ast.Dict: self.handle_dict,51 ast.List: self.handle_list,52 ast.Tuple: self.handle_list,53 ast.And: self.handle_and,54 ast.Or: self.handle_or,55 ast.Not: self.handle_not56 }5758 def indent(self, text):59 """60 Indent the current text.61 """62 return (' ' * (self.indention * 4)) + text6364 def handle_node(self, node):65 """66 Handle one node67 """68 if node.__class__ in self.handlers:69 out = self.handlers[node.__class__](node)70 else:71 raise AssertionError('unhandled node %r' % node.__class__)72 return out7374 # -- jinja nodes7576 def handle_node_list(self, node):77 """78 In some situations we might have a node list. It's just79 a collection of multiple statements.80 """81 self.last_pos = node.pos82 buf = []83 for n in node:84 buf.append(self.handle_node(n))85 return '\n'.join(buf)8687 def handle_for_loop(self, node):88 """89 Handle a for loop. Pretty basic, just that we give the else90 clause a different behavior.91 """92 self.last_pos = node.pos93 buf = []94 write = lambda x: buf.append(self.indent(x))95 write('context.push()')96 write('parent_loop = context[\'loop\']')97 write('loop_data = None')98 write('for (loop_data, %s) in environment.iterate(%s):' % (99 self.handle_node(node.item),100 self.handle_node(node.seq)101 ))102 self.indention += 1103 write('loop_data.parent = parent_loop')104 write('context[\'loop\'] = loop_data')105 buf.append(self.handle_node(node.body))106 self.indention -= 1107 if node.else_ is not None:108 write('if loop_data is None:')109 self.indention += 1110 buf.append(self.handle_node(node.else_))111 self.indention -= 1112 write('context.pop()')113 return '\n'.join(buf)114115 def handle_if_condition(self, node):116 """117 Handle an if condition node.118 """119 self.last_pos = node.pos120 buf = []121 write = lambda x: buf.append(self.indent(x))122 write('if %s:' % self.handle_node(node.test))123 self.indention += 1124 buf.append(self.handle_node(node.body))125 self.indention -= 1126 if node.else_ is not None:127 write('else:')128 self.indention += 1129 buf.append(self.handle_node(node.else_))130 self.indention -= 1131 return '\n'.join(buf)132133 def handle_print(self, node):134 """135 Handle a print statement.136 """137 self.last_pos = node.pos138 return self.indent('write_var(%s)' % self.handle_node(node.variable))139140 def handle_template_text(self, node):141 """142 Handle data around nodes.143 """144 self.last_pos = node.pos145 return self.indent('write(%r)' % node.text)146147 # -- python nodes148149 def handle_name(self, node):150 """151 Handle name assignments and name retreivement.152 """153 return 'context[%r]' % node.name154155 def handle_compare(self, node):156 """157 Any sort of comparison158 """159 buf = []160 buf.append(self.handle_node(node.expr))161 for op, n in node.ops:162 buf.append(op)163 buf.append(self.handle_node(n))164 return ' '.join(buf)165166 def handle_const(self, node):167 """168 Constant values in expressions.169 """170 return repr(node.value)171172 def handle_subscript(self, node):173 """174 Handle variable based attribute access foo['bar'].175 """176 if len(node.subs) != 1:177 raise TemplateSyntaxError('attribute access requires one argument',178 self.last_pos)179 assert node.flags != 'OP_DELETE', 'wtf? do we support that?'180 return 'get_attribute(%s, %s)' % (181 self.handle_node(node.expr),182 self.handle_node(node.subs[0])183 )184185 def handle_getattr(self, node):186 """187 Handle hardcoded attribute access. foo.bar188 """189 return 'get_attribute(%s, %r)' % (190 self.handle_node(node.expr),191 node.attrname192 )193194 def handle_ass_tuple(self, node):195 """196 Tuple unpacking loops.197 """198 return '(%s)' % ', '.join([self.handle_node(n) for n in node.nodes])199200 def handle_bitor(self, node):201 """202 We use the pipe operator for filtering.203 """204 return 'environment.apply_filters(%s, %r)' % (205 self.handle_node(node.nodes[0]),206 [self.handle_node(n) for n in node.nodes[1:]]207 )208209 def handle_call_func(self, node):210 """211 Handle function calls.212 """213 args = []214 kwargs = {}215 star_args = dstar_args = None216 if node.star_args is not None:217 star_args = self.handle_node(node.star_args)218 if node.dstar_args is not None:219 dstar_args = self.handle_node(node.dstar_args)220 for arg in node.args:221 if arg.__class__ is ast.Keyword:222 kwargs[arg.name] = self.handle_node(arg.expr)223 else:224 args.append(self.handle_node(arg))225 return 'environment.call_function(%s, [%s], {%s}, %s, %s)' % (226 self.handle_node(node.node),227 ', '.join(args),228 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),229 star_args,230 dstar_args231 )232233 def handle_add(self, node):234 """235 Add two items.236 """237 return '(%s + %s)' % (238 self.handle_node(node.left),239 self.handle_node(node.right)240 )241242 def handle_sub(self, node):243 """244 Sub two items.245 """246 return '(%s - %s)' % (247 self.handle_node(node.left),248 self.handle_node(node.right)249 )250251 def handle_div(self, node):252 """253 Divide two items.254 """255 return '(%s / %s)' % (256 self.handle_node(node.left),257 self.handle_node(node.right)258 )259260 def handle_mul(self, node):261 """262 Multiply two items.263 """264 return '(%s * %s)' % (265 self.handle_node(node.left),266 self.handle_node(node.right)267 )268269 def handle_mod(self, node):270 """271 Apply modulo.272 """273 return '(%s %% %s)' % (274 self.handle_node(node.left),275 self.handle_node(node.right)276 )277278 def handle_unary_sub(self, node):279 """280 Make a number negative.281 """282 return '(-%s)' % self.handle_node(node.expr)283284 def handle_power(self, node):285 """286 handle foo**bar287 """288 return '(%s**%s)' % (289 self.handle_node(node.left),290 self.handle_node(node.right)291 )292293 def handle_dict(self, node):294 """295 Dict constructor syntax.296 """297 return '{%s}' % ', '.join([298 '%s: %s' % (299 self.handle_node(key),300 self.handle_node(value)301 ) for key, value in node.items302 ])303304 def handle_list(self, node):305 """306 We don't know tuples, tuples are lists for jinja.307 """308 return '[%s]' % ', '.join([309 self.handle_node(n) for n in nodes310 ])311312 def handle_and(self, node):313 """314 Handle foo and bar.315 """316 return ' and '.join([317 self.handle_node(n) for n in node.nodes318 ])319320 def handle_or(self, node):321 """322 handle foo or bar.323 """324 return ' or '.join([325 self.handle_node(n) for n in self.nodse326 ])327328 def handle_not(self, node):329 """330 handle not operator.331 """332 return 'not %s' % self.handle_node(node.expr)333334 def translate(self):335 self.indention = 1336 lines = [337 'def generate(environment, context, write, write_var=None):',338 ' """This function was automatically generated by',339 ' the jinja python translator. do not edit."""',340 ' if write_var is None:',341 ' write_var = write'342 ]343 lines.append(self.handle_node(self.node))344 return '\n'.join(lines)345346347def translate(environment, node):348 """349 Do the translation to python.350 """351 return PythonTranslator(environment, node).translate()
added:jinja/__init__.py+8 added
1# -*- coding: utf-8 -*-2"""3 Jinja Sandboxed Template Engine4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2006 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""
added:jinja/ast.py+108 added
1# -*- coding: utf-8 -*-2"""3 jinja.ast4 ~~~~~~~~~56 Advance Syntax Tree for jinja.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112class Node(object):13 """14 Baseclass of all nodes. For instance checking.15 """16 __slots__ = ()1718 def __init__(self):19 raise TypeError('cannot create %r instances' %20 self.__class__.__name__)212223class Expression(list, Node):24 """25 Node that helds childnodes. Normally just used temporary.26 """27 __slots__ = ()2829 def __init__(self, *args, **kwargs):30 super(Expression, self).__init__(*args, **kwargs)3132 def __repr__(self):33 return 'Expression(%s)' % list.__repr__(self)343536class Comment(Node):37 """38 Node that helds a comment. We keep comments in the data39 if some translator wants to forward it into the generated40 code (for example the python translator).41 """42 __slots__ = ('pos', 'comment',)4344 def __init__(self, pos, comment):45 self.pos = pos46 self.comment = comment4748 def __repr__(self):49 return 'Comment(%r, %r)' % (self.pos, self.comment)505152class Page(Node):53 """54 Node that helds all root nodes.55 """56 __slots__ = ('filename', 'nodes')5758 def __init__(self, filename, nodes):59 self.filename = filename60 self.nodes = nodes6162 def __repr__(self):63 return 'Page(%r, %r)' % (64 self.filename,65 self.nodes66 )676869class Variable(Node):70 """71 Node for variables72 """73 __slots__ = ('pos', 'expression')7475 def __init__(self, pos, expression):76 self.pos = pos77 self.expression = expression7879 def __repr__(self):80 return 'Variable(%r)' % self.expression818283class Data(Node):84 """85 Node for data outside of tags.86 """87 __slots__ = ('pos', 'data')8889 def __init__(self, pos, data):90 self.pos = pos91 self.data = data9293 def __repr__(self):94 return 'Data(%d, %r)' % (self.pos, self.data)959697class Name(Node):98 """99 Node for names.100 """101 __slots__ = ('pos', 'data')102103 def __init__(self, pos, data):104 self.pos = pos105 self.data = data106107 def __repr__(self):108 return 'Name(%d, %r)' % (self.pos, self.data)
added:jinja/datastructure.py+175 added
1# -*- coding: utf-8 -*-2"""3 jinja.datastructure4 ~~~~~~~~~~~~~~~~~~~56 Module that helds several data types used in the template engine.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112# python2.3 compatibility. do not use this method for anything else13# then context reversing.14try:15 _reversed = reversed16except NameError:17 def _reversed(c):18 return c[::-1]192021class UndefinedType(object):22 """23 An object that does not exist.24 """2526 def __init__(self):27 try:28 Undefined29 except NameError:30 pass31 else:32 raise TypeError('cannot create %r instances' %33 self.__class__.__name__)3435 def __getitem__(self, arg):36 return self3738 def __iter__(self):39 return iter(int, 0)4041 def __getattr__(self, arg):42 return self4344 def __nonzero__(self):45 return False4647 def __len__(self):48 return 04950 def __str__(self):51 return ''5253 def __unicode__(self):54 return u''5556 def __int__(self):57 return 05859 def __float__(self):60 return 1616263Undefined = UndefinedType()646566class Context(object):67 """68 Dict like object.69 """7071 __slots__ = ('stack')7273 def __init__(*args, **kwargs):74 try:75 self = args[0]76 self.environment = args[1]77 initial = dict(*args[2:], **kwargs)78 except:79 raise TypeError('%r requires environment as first argument. '80 'The rest of the arguments are forwarded to '81 'the default dict constructor.')82 initial.update(83 false=False,84 true=True,85 none=None86 )87 self._stack = [initial, {}]8889 def pop(self):90 if len(self._stack) <= 2:91 raise ValueError('cannot pop initial layer')92 return self._stack.pop()9394 def push(self, data=None):95 self._stack.append(data or {})9697 def __getitem__(self, name):98 for d in _reversed(self._stack):99 if name in d:100 return d[name]101 return Undefined102103 def __setitem__(self, name, value):104 self._stack[-1][name] = value105106 def __delitem__(self, name):107 if name in self._stack[-1]:108 del self._stack[-1][name]109110 def __repr__(self):111 tmp = {}112 for d in self._stack:113 for key, value in d.iteritems():114 tmp[key] = value115 return 'Context(%s)' % repr(tmp)116117118class TokenStream(object):119 """120 A token stream works like a normal generator just that121 it supports pushing tokens back to the stream.122 """123124 def __init__(self, generator):125 self._generator = generator126 self._pushed = []127 self.last = (0, 'initial', '')128129 def __iter__(self):130 return self131132 def __nonzero__(self):133 """Are we at the end of the tokenstream?"""134 if self._pushed:135 return True136 try:137 self.push(self.next())138 except StopIteration:139 return False140 return True141142 eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)143144 def next(self):145 """Return the next token from the stream."""146 if self._pushed:147 rv = self._pushed.pop()148 else:149 rv = self._generator.next()150 self.last = rv151 return rv152153 def look(self):154 """Pop and push a token, return it."""155 token = self.next()156 self.push(*token)157 return token158159 def fetch_until(self, test, drop_needle=False):160 """Fetch tokens until a function matches."""161 try:162 while True:163 token = self.next()164 if test(*token):165 if not drop_needle:166 self.push(*token)167 return168 else:169 yield token170 except StopIteration:171 raise IndexError('end of stream reached')172173 def push(self, pos, token, data):174 """Push an yielded token back to the stream."""175 self._pushed.append((pos, token, data))
added:jinja/defaults.py+15 added
1# -*- coding: utf-8 -*-2"""3 jinja.defaults4 ~~~~~~~~~~~~~~56 Jinja default filters and tags.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213DEFAULT_TAGS = {}1415DEFAULT_FILTERS = {}
added:jinja/environment.py+86 added
1# -*- coding: utf-8 -*-2"""3 jinja.environment4 ~~~~~~~~~~~~~~~~~56 Provides a class that holds runtime and parsing time options.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.lexer import Lexer12from jinja.parser import Parser13from jinja.exceptions import TagNotFound, FilterNotFound14from jinja.defaults import DEFAULT_TAGS, DEFAULT_FILTERS151617class Environment(object):18 """19 The jinja environment.20 """2122 def __init__(self,23 block_start_string='{%',24 block_end_string='%}',25 variable_start_string='{{',26 variable_end_string='}}',27 comment_start_string='{#',28 comment_end_string='#}',29 template_charset='utf-8',30 charset='utf-8',31 loader=None,32 tags=None,33 filters=None):3435 # lexer / parser information36 self.block_start_string = block_start_string37 self.block_end_string = block_end_string38 self.variable_start_string = variable_start_string39 self.variable_end_string = variable_end_string40 self.comment_start_string = comment_start_string41 self.comment_end_string = comment_end_string4243 # other stuff44 self.template_charset = template_charset45 self.charset = charset46 self.loader = loader47 self.tags = tags or DEFAULT_TAGS.copy()48 self.filters = filters or DEFAULT_FILTERS.copy()4950 # create lexer51 self.lexer = Lexer(self)5253 def parse(self, source):54 """Function that creates a new parser and parses the source."""55 parser = Parser(self, source)56 return parser.parse_page()5758 def get_tag(self, name):59 """60 Return the tag for a specific name. Raise a `TagNotFound` exception61 if a tag with this name is not registered.62 """63 if name not in self._tags:64 raise TagNotFound(name)65 return self._tags[name]6667 def get_filter(self, name):68 """69 Return the filter for a given name. Raise a `FilterNotFound` exception70 if the requested filter is not registered.71 """72 if name not in self._filters:73 raise FilterNotFound(name)74 return self._filters[name]7576 def to_unicode(self, value):77 """78 Convert a value to unicode with the rules defined on the environment.79 """80 if isinstance(value, unicode):81 return value82 else:83 try:84 return unicode(value)85 except UnicodeError:86 return str(value).decode(self.charset, 'ignore')
added:jinja/exceptions.py+56 added
1# -*- coding: utf-8 -*-2"""3 jinja.exceptions4 ~~~~~~~~~~~~~~~~56 Jinja exceptions.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213class TemplateError(RuntimeError):14 pass151617class TagNotFound(KeyError, TemplateError):18 """19 The parser looked for a specific tag in the tag library but was unable to find20 one.21 """2223 def __init__(self, tagname):24 super(TagNotFound, self).__init__('The tag %r does not exist.' % tagname)25 self.tagname = tagname262728class FilterNotFound(KeyError, TemplateError):29 """30 The template engine looked for a filter but was unable to find it.31 """3233 def __init__(self, filtername):34 super(FilterNotFound, self).__init__('The filter %r does not exist.' % filtername)35 self.filtername = filtername363738class TemplateSyntaxError(SyntaxError, TemplateError):39 """40 Raised to tell the user that there is a problem with the template.41 """4243 def __init__(self, message, pos):44 super(TemplateSyntaxError, self).__init__(message)45 self.pos = pos464748class TemplateRuntimeError(TemplateError):49 """50 Raised by the template engine if a tag encountered an error when51 rendering.52 """5354 def __init__(self, message, pos):55 super(TemplateRuntimeError, self).__init__(message)56 self.pos = pos
added:jinja/filters.py+203 added
1# -*- coding: utf-8 -*-2"""3 jinja.filters4 ~~~~~~~~~~~~~56 Bundled jinja filters.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213def stringfilter(f):14 """15 Decorator for filters that just work on unicode objects.16 """17 def decorator(*args):18 def wrapped(env, context, value):19 args = list(args)20 for idx, var in enumerate(args):21 if isinstance(var, str):22 args[idx] = env.to_unicode(var)23 return f(env.to_unicode(value), *args)24 return wrapped25 return decorator262728def do_replace(s, old, new, count=None):29 """30 {{ s|replace(old, new, count=None) }}3132 Return a copy of s with all occurrences of substring33 old replaced by new. If the optional argument count is34 given, only the first count occurrences are replaced.35 """36 if count is None:37 return s.replace(old, new)38 return s.replace(old, new, count)39do_replace = stringfilter(do_replace)404142def do_upper(s):43 """44 {{ s|upper }}4546 Return a copy of s converted to uppercase.47 """48 return s.upper()49do_upper = stringfilter(do_upper)505152def do_lower(s):53 """54 {{ s|lower }}5556 Return a copy of s converted to lowercase.57 """58 return s.lower()59do_lower = stringfilter(do_lower)606162def do_escape(s, attribute=False):63 """64 {{ s|escape(attribute) }}6566 XML escape &, <, and > in a string of data. If attribute is67 True it also converts ``"`` to ``&quot;``68 """69 s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")70 if attribute:71 s = s.replace('"', "&quot;")72 return s73do_escape = stringfilter(do_escape)747576def do_addslashes(s):77 """78 {{ s|addslashes }}7980 Adds slashes to s.81 """82 return s.encode('utf-8').encode('string-escape').decode('utf-8')83do_addslashes = stringfilter(do_addslashes)848586def do_capitalize(s):87 """88 {{ s|capitalize }}8990 Return a copy of the string s with only its first character91 capitalized.92 """93 return s.capitalize()94do_capitalize = stringfilter(do_capitalize)959697def do_title(s):98 """99 {{ s|title }}100101 Return a titlecased version of s, i.e. words start with uppercase102 characters, all remaining cased characters have lowercase.103 """104 return s.title()105do_title = stringfilter(do_title)106107108def do_default(default_value=u''):109 """110 {{ s|default(default_value='') }}111112 In case of s isn't set or True default will return default_value113 which is '' per default.114 """115 return lambda e, c, v: v or default_value116117118def do_join(d=u''):119 """120 {{ sequence|join(d='') }}121122 Return a string which is the concatenation of the strings in the123 sequence. The separator between elements is d which is an empty124 string per default.125 """126 def wrapped(env, context, value):127 d = env.to_unicode(d)128 return d.join([env.to_unicode(x) for x in value])129 return wrapped130131132def do_count():133 """134 {{ var|count }}135136 Return the length of var. In case if getting an integer or float137 it will convert it into a string an return the length of the new138 string.139 If the object doesn't provide a __len__ function it will return140 zero.st(value)141 l.reverse()142 return 143 """144 def wrapped(env, context, value):145 try:146 if type(value) in (int, float, long):147 return len(str(var))148 return len(var)149 except TypeError:150 return 0151 return wrapped152153154def do_odd():155 """156 {{ var|odd }}157158 Return true if the variable is odd.159 """160 return lambda e, c, v: v % 2 == 1161162163def do_even():164 """165 {{ var|even }}166167 Return true of the variable is even.168 """169 return lambda e, c, v: v % 2 == 0170171172def do_reversed():173 """174 {{ var|reversed }}175176 Return a reversed list of the iterable filtered.177 """178 def wrapped(env, context, value):179 try:180 return value[::-1]181 except:182 l = list(value)183 l.reverse()184 return l185 return wrapped186187188FILTERS = {189 'replace': do_replace,190 'upper': do_upper,191 'lower': do_lower,192 'escape': do_escape,193 'e': do_escape,194 'addslashes': do_addslashes,195 'capitalize': do_capitalize,196 'title': do_title,197 'default': do_default,198 'join': do_join,199 'count': do_count,200 'odd': do_odd,201 'even': do_even,202 'reversed': do_reversed203}
added:jinja/lexer.py+191 added
1# -*- coding: utf-8 -*-2"""3 jinja.lexer4 ~~~~~~~~~~~5"""6import re7from jinja.datastructure import TokenStream8from jinja.exceptions import TemplateSyntaxError91011# static regular expressions12whitespace_re = re.compile(r'\s+(?m)')13name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*[!?]?')14string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"15 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')16number_re = re.compile(r'\d+(\.\d+)*')1718operator_re = re.compile('(%s)' % '|'.join(19 isinstance(x, unicode) and str(x) or re.escape(x) for x in [20 # math operators21 '+', '-', '*', '/', '%',22 # braces and parenthesis23 '[', ']', '(', ')', '{', '}',24 # attribute access and comparison / logical operators25 '.', ',', '|', '==', '<', '>', '<=', '>=', '!=',26 ur'or\b', ur'and\b', ur'not\b'27]))282930class Failure(object):31 """32 Class that raises a `TemplateSyntaxError` if called.33 Used by the `Lexer` to specify known errors.34 """3536 def __init__(self, message, cls=TemplateSyntaxError):37 self.message = message38 self.error_class = cls3940 def __call__(self, position):41 raise self.error_class(self.message, position)424344class Lexer(object):45 """46 Class that implements a lexer for a given environment. Automatically47 created by the environment class, usually you don't have to do that.48 """4950 def __init__(self, environment):51 # shortcuts52 c = lambda x: re.compile(x, re.M | re.S)53 e = re.escape5455 # parsing rules for tags56 tag_rules = [57 (whitespace_re, None, None),58 (number_re, 'number', None),59 (operator_re, 'operator', None),60 (name_re, 'name', None),61 (string_re, 'string', None)62 ]6364 # global parsing rules65 self.rules = {66 'root': [67 (c('(.*?)(?:(?P<comment_begin>' +68 e(environment.comment_start_string) +69 ')|(?P<block_begin>' +70 e(environment.block_start_string) +71 ')|(?P<variable_begin>' +72 e(environment.variable_start_string) +73 '))'), ('data', '#bygroup'), '#bygroup'),74 (c('.+'), 'data', None)75 ],76 'comment_begin': [77 (c(r'(.*?)(%s)' % e(environment.comment_end_string)),78 ('comment', 'comment_end'), '#pop'),79 (c('(.)'), (Failure('Missing end of comment tag'),), None)80 ],81 'block_begin': [82 (c(e(environment.block_end_string)), 'block_end', '#pop')83 ] + tag_rules,84 'variable_begin': [85 (c(e(environment.variable_end_string)), 'variable_end',86 '#pop')87 ] + tag_rules88 }8990 def tokenize(self, source):91 """92 Simple tokenize function that yields ``(position, type, contents)``93 tuples. Wrap the generator returned by this function in a94 `TokenStream` to get real token instances and be able to push tokens95 back to the stream. That's for example done by the parser.96 """97 return TokenStream(self.tokeniter(source))9899 def tokeniter(self, source):100 """101 This method tokenizes the text and returns the tokens in a generator.102 Normally it's a better idea to use the `tokenize` function which103 returns a `TokenStream` but in some situations it can be useful104 to use this function since it can be marginally faster.105 """106 pos = 0107 stack = ['root']108 statetokens = self.rules['root']109 source_length = len(source)110111 while True:112 # tokenizer loop113 for regex, tokens, new_state in statetokens:114 m = regex.match(source, pos)115 if m:116 # tuples support more options117 if isinstance(tokens, tuple):118 for idx, token in enumerate(tokens):119 # hidden group120 if token is None:121 continue122 # failure group123 elif isinstance(token, Failure):124 raise token(m.start(idx + 1))125 # bygroup is a bit more complex, in that case we126 # yield for the current token the first named127 # group that matched128 elif token == '#bygroup':129 for key, value in m.groupdict().iteritems():130 if value is not None:131 yield m.start(key), key, value132 break133 else:134 raise RuntimeError('%r wanted to resolve '135 'the token dynamically'136 ' but no group matched'137 % regex)138 # normal group139 else:140 data = m.group(idx + 1)141 if data:142 yield m.start(idx + 1), token, data143 # strings as token just are yielded as it, but just144 # if the data is not empty145 else:146 data = m.group()147 if tokens is not None:148 if data:149 yield pos, tokens, data150 # fetch new position into new variable so that we can check151 # if there is a internal parsing error which would result152 # in an infinite loop153 pos2 = m.end()154 # handle state changes155 if new_state is not None:156 # remove the uppermost state157 if new_state == '#pop':158 stack.pop()159 # resolve the new state by group checking160 elif new_state == '#bygroup':161 for key, value in m.groupdict().iteritems():162 if value is not None:163 stack.append(key)164 break165 else:166 raise RuntimeError('%r wanted to resolve the '167 'new state dynamically but'168 ' no group matched' %169 regex)170 # direct state name given171 else:172 stack.append(new_state)173 statetokens = self.rules[stack[-1]]174 # we are still at the same position and no stack change.175 # this means a loop without break condition, avoid that and176 # raise error177 elif pos2 == pos:178 raise RuntimeError('%r yielded empty string without '179 'stack change' % regex)180 # publish new function and start again181 pos = pos2182 break183 # if loop terminated without break we havn't found a single match184 # either we are at the end of the file or we have a problem185 else:186 # end of text187 if pos >= source_length:188 return189 # something went wrong190 raise TemplateSyntaxError('unexpected char %r at %d' %191 (source[pos], pos), pos)
added:jinja/nodes.py+90 added
1# -*- coding: utf-8 -*-2"""3 jinja.nodes4 ~~~~~~~~~~~56 Additional nodes for jinja. Look like nodes from the ast.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from compiler.ast import Node121314class Text(Node):15 """16 Node that represents normal text.17 """1819 def __init__(self, pos, text):20 self.pos = pos21 self.text = text2223 def __repr__(self):24 return 'Text(%r)' % (self.text,)252627class NodeList(list, Node):28 """29 A node that stores multiple childnodes.30 """3132 def __init__(self, pos, data=None):33 self.pos = pos34 list.__init__(self, data or ())3536 def __repr__(self):37 return 'NodeList(%s)' % list.__repr__(self)383940class ForLoop(Node):41 """42 A node that represents a for loop43 """4445 def __init__(self, pos, item, seq, body, else_):46 self.pos = pos47 self.item = item48 self.seq = seq49 self.body = body50 self.else_ = else_5152 def __repr__(self):53 return 'ForLoop(%r, %r, %r, %r)' % (54 self.item,55 self.seq,56 self.body,57 self.else_58 )596061class IfCondition(Node):62 """63 A node that represents an if condition.64 """6566 def __init__(self, pos, test, body, else_):67 self.pos = pos68 self.test = test69 self.body = body70 self.else_ = else_7172 def __repr__(self):73 return 'IfCondition(%r, %r, %r)' % (74 self.test,75 self.body,76 self.else_77 )787980class Print(Node):81 """82 A node that represents variable tags and print calls83 """8485 def __init__(self, pos, variable):86 self.pos = pos87 self.variable = variable8889 def __repr__(self):90 return 'Print(%r)' % (self.variable,)
added:jinja/parser.py+219 added
1# -*- coding: utf-8 -*-2"""3 jinja.parser4 ~~~~~~~~~~~~56 Implements the template parser.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from compiler import ast, parse13from jinja import nodes14from jinja.datastructure import TokenStream15from jinja.exceptions import TemplateSyntaxError161718# callback functions for the subparse method19end_of_block = lambda p, t, d: t == 'block_end'20end_of_variable = lambda p, t, d: t == 'variable_end'21switch_for = lambda p, t, d: t == 'name' and d in ('else', 'endfor')22end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'23switch_if = lambda p, t, d: t == 'name' and d in ('else', 'endif')24end_of_if = lambda p, t, d: t == 'name' and d == 'endif'252627class Parser(object):28 """29 The template parser class.3031 Transforms sourcecode into an abstract syntax tree::3233 >>> parse("{% for item in seq|reversed %}{{ item }}{% endfor %}")34 Document(ForLoop(AssignName('item'), Filter(Name('seq'), Name('reversed')),35 Print('item'), None))36 >>> parse("{% if true %}foo{% else %}bar{% endif %}")37 Document(IfCondition(Name('true'), Data('foo'), Data('bar')))38 >>> parse("{% if false %}...{% elif 0 > 1 %}...{% else %}...{% endif %}")39 Document(IfCondition(Name('false'), Data('...'),40 IfCondition(Compare('>', Const(0), Const(1)),41 Data('...'), Data('...'))))42 """4344 def __init__(self, environment, source, filename=None):45 self.environment = environment46 if isinstance(source, str):47 source = source.decode(environment.template_charset, 'ignore')48 self.source = source49 self.filename = filename50 self.tokenstream = environment.lexer.tokenize(source)51 self._parsed = False5253 self.directives = {54 'for': self.handle_for_directive,55 'if': self.handle_if_directive,56 'print': self.handle_print_directive57 }5859 def handle_for_directive(self, pos, gen):60 """61 Handle a for directive and return a ForLoop node62 """63 ast = self.parse_python(pos, gen, 'for %s:pass\nelse:pass')64 body = self.subparse(switch_for)6566 # do we have an else section?67 if self.tokenstream.next()[2] == 'else':68 self.close_remaining_block()69 else_ = self.subparse(end_of_for, True)70 else:71 else_ = None72 self.close_remaining_block()7374 return nodes.ForLoop(pos, ast.assign, ast.list, body, else_)7576 def handle_if_directive(self, pos, gen):77 """78 Handle if/else blocks. elif is not supported by now.79 """80 ast = self.parse_python(pos, gen, 'if %s:pass\nelse:pass')81 body = self.subparse(switch_if)8283 # do we have an else section?84 if self.tokenstream.next()[2] == 'else':85 self.close_remaining_block()86 else_ = self.subparse(end_of_if, True)87 else:88 else_ = None89 self.close_remaining_block()9091 return nodes.IfCondition(pos, ast.tests[0][0], body, else_)9293 def handle_print_directive(self, pos, gen):94 """95 Handle {{ foo }} and {% print foo %}.96 """97 ast = self.parse_python(pos, gen, 'print_(%s)')98 # ast is something like Discard(CallFunc(Name('print_'), ...))99 # so just use the args100 arguments = ast.expr.args101 # we only accept one argument102 if len(arguments) != 1:103 raise TemplateSyntaxError('invalid argument count for print; '104 'print requires exactly one argument, '105 'got %d.' % len(arguments), pos)106 return nodes.Print(pos, arguments[0])107108 def parse_python(self, pos, gen, template='%s'):109 """110 Convert the passed generator into a flat string representing111 python sourcecode and return an ast node or raise a112 TemplateSyntaxError.113 """114 tokens = []115 for t_pos, t_token, t_data in gen:116 if t_token == 'string':117 tokens.append('u' + t_data)118 else:119 tokens.append(t_data)120 source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).encode('utf-8'))121 try:122 ast = parse(source, 'exec')123 except SyntaxError, e:124 raise TemplateSyntaxError(str(e), pos + e.offset - 1)125 assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % len(ast.node.nodes)126 return ast.node.nodes[0]127128 def parse(self):129 """130 Parse the template and return a nodelist.131 """132 return self.subparse(None)133134 def subparse(self, test, drop_needle=False):135 """136 Helper function used to parse the sourcecode until the test137 function which is passed a tuple in the form (pos, token, data)138 returns True. In that case the current token is pushed back to139 the tokenstream and the generator ends.140141 The test function is only called for the first token after a142 block tag. Variable tags are *not* aliases for {% print %} in143 that case.144145 If drop_needle is True the needle_token is removed from the tokenstream.146 """147 def finish():148 """Helper function to remove unused nodelists."""149 if len(result) == 1:150 return result[0]151 return result152153 pos = self.tokenstream.last[0]154 result = nodes.NodeList(pos)155 for pos, token, data in self.tokenstream:156 # this token marks the begin or a variable section.157 # parse everything till the end of it.158 if token == 'variable_begin':159 gen = self.tokenstream.fetch_until(end_of_variable, True)160 result.append(self.directives['print'](pos, gen))161162 # this token marks the start of a block. like for variables163 # just parse everything until the end of the block164 elif token == 'block_begin':165 gen = self.tokenstream.fetch_until(end_of_block, True)166 try:167 pos, token, data = gen.next()168 except StopIteration:169 raise TemplateSyntaxError('unexpected end of block', pos)170171 # first token *must* be a name token172 if token != 'name':173 raise TemplateSyntaxError('unexpected %r token' % token, pos)174175 # if a test function is passed to subparse we check if we176 # reached the end of such a requested block.177 if test is not None and test(pos, token, data):178 if not drop_needle:179 self.tokenstream.push(pos, token, data)180 return finish()181182 # the first token tells us which directive we want to call.183 # if if doesn't match any existing directive it's like a184 # template syntax error.185 if data in self.directives:186 node = self.directives[data](pos, gen)187 else:188 raise TemplateSyntaxError('unknown directive %r' % data, pos)189 result.append(node)190191 # here the only token we should get is "data". all other192 # tokens just exist in block or variable sections. (if the193 # tokenizer is not brocken)194 elif token == 'data':195 result.append(nodes.Text(pos, data))196197 # so this should be unreachable code198 else:199 raise AssertionError('unexpected token %r' % token)200201 # still here and a test function is provided? raise and error202 if test is not None:203 raise TemplateSyntaxError('unexpected end of template', pos)204 return finish()205206 def close_remaining_block(self):207 """208 If we opened a block tag because one of our tags requires an end209 tag we can use this method to drop the rest of the block from210 the stream. If the next token isn't the block end we throw an211 error.212 """213 pos = self.tokenstream.last[0]214 try:215 pos, token, data = self.tokenstream.next()216 except StopIteration:217 raise TemplateSyntaxError('missing closing tag', pos)218 if token != 'block_end':219 raise TemplateSyntaxError('expected close tag, found %r' % token, pos)
added:tests/mockup.txt+153 added
1source index.html::23 {% page extends='layout.html', defaultfilter='autoescape',4 charset='utf-8' %}56 {% def title %}Index | {{ super.title }}{% enddef %}7 {% def body %}8 <h1>Index</h1>9 <p>10 This is just a mockup template so that you can see how the new11 jinja syntax looks like. It also shows the python output of this12 template when compiled.13 </p>14 <ul>15 {% for user in users %}16 <li class="{% cycle 'row1', 'row2' %}">{{ user.username }}</li>17 {% endfor %}18 </ul>19 {% enddef %}2021source layout.html::2223 {% page defaultfilter='autoescape', charset='utf-8' %}24 <html>25 <head>26 <title>{% block title %}My Webpage{% endblock %}</title>27 </head>28 <body>29 <div class="header">30 <h1>My Webpage</h1>31 <h2>{{ self.title }}</h2>32 </div>33 <div class="body">34 {{ self.body }}35 </div>36 <div class="footer">37 {% block footer %}38 Copyright 2007 by the Pocoo Team.39 {% endblock %}40 </div>41 </body>42 </html>4344generated python code::4546 from jinja.runtime import Template, Markup4748 class Layer1Template(Template):4950 defaultfilter = 'autoescape'5152 def p_title(self):53 yield Markup(u'My Webpage')5455 def p_footer(self):56 yield Markup(u'\n Copyright 2007 by the Pocoo Team.\n ')5758 def p_outer_body(self):59 yield Markup(u'<html>\n <head>\n <title>\n')60 for i in self.resolve('self.title'):61 yield i62 yield Markup(u'</title>\n </head>\n <body>\n <div class="header">\n'63 u' <h1>My Webpage</h1>\n <h2>')64 for i in self.resolve('self.title'):65 yield i66 yield Markup(u'</h2>\n </div>\n <div class="body">\n ')67 for i in self.resolve('self.body'):68 yield i69 yield Markup(u'\n </div>\n <div class="footer">\n ')70 for i in self.resolve('self.footer'):71 yield i72 yield Markup(u'\n </div>\n </body>\n</html')7374 class Layer2Template(Layer1Template):7576 defaultfilter = 'autoescape'7778 def p_title(self):79 yield Markup(u'Index | ')80 for i in self.resolve('super.title'):81 yield i8283 def p_body(self):84 yield Markup(u'\n <h1>Index</h1>\n <p>\n This is just a mockup '85 u'template so that you can see how the new jinja syntax '86 u'looks like. It also shows the python output of this '87 u'template when compiled.\n </p>\n <ul>\n ')88 iteration_1 = self.start_iteration(['user'], 'users')89 for _ in iteration_1:90 yield Markup(u'\n <li class="')91 for i in self.cycle(u'row1', u'row2'):92 yield i93 yield Markup(u'">')94 for i in self.resolve('user.username'):95 yield i96 yield Markup(u'</li>\n ')97 iteration_1.close()9899 def get_template(context):100 return Layer2Template(context)101102generated javascript code::103104 (function(c) {105 var m = function(x) { return new Jinja.Markup(x) };106107 var l1 = function() {};108 l1.defaultfilter = 'autoescape';109 l1.prototype.p_title = function() {110 this.yield(m('My Webpage'));111 };112 l1.prototype.p_footer = function() {113 this.yield(m('\n Copyright 2007 by the Pocoo Team.\n '));114 };115 l1.prototype.p_outer_body = function() {116 this.yield(m('<html>\n <head>\n <title>\n'));117 this.resolve('self.title');118 this.yield(m('</title>\n </head>\n <body>\n <div class="header">\n'119 ' <h1>My Webpage</h1>\n <h2>'));120 this.resolve('self.title');121 this.yield(m('</h2>\n </div>\n <div class="body">\n '));122 this.resolve('self.body');123 this.yield(m('\n </div>\n <div class="footer">\n '));124 this.resolve('self.footer');125 this.yield(m('\n </div>\n </body>\n</html'));126 };127128 var l2 = function() {};129 l2.defaultfilter = 'autoescape';130 l2.prototype.p_title = function() {131 this.yield(m('Index | '));132 this.resolve('super.title');133 };134 l2.prototype.p_body = function() {135 this.yield(m('\n <h1>Index</h1>\n <p>\n This is just a mockup '136 'template so that you can see how the new jinja syntax '137 'looks like. It also shows the python output of this '138 'template when compiled.\n </p>\n <ul>\n '));139 var iteration_1 = this.startIteration(['user'], 'users');140 while (iteration_1.next()) {141 this.yield(m('\n <li class="'));142 this.cycle('row1', 'row2');143 this.yield(m('">'));144 this.resolve('user.username');145 this.yield('</li>\n ');146 };147 iteration_1.close();148 };149150 return function(context) {151 return new Jinja.Template(context, l1, l2);152 };153 })();
added:tests/run.py+15 added
1from jinja import Environment, FileSystemLoader23env = Environment(4 loader=FileSystemLoader(['.'], suffix='')5)6env.filters['odd?'] = lambda c, x: x % 2 == 17env.filters['even?'] = lambda x, x: x % 2 == 089t = env.get_template('index.html')10print t.render(11 users=[12 dict(username='foo', user_id=1),13 dict(username='bar', user_id=2)14 ]15)
added:syntax.html+61 added
added:syntax.txt+22 added
1For Loops2---------34Simple Syntax::56 {% for <item> in <seq> %}7 <data>8 {% endfor %}910Item Unpacking::1112 {% for <item1>, <item2> in <seq> %}13 <data>14 {% endfor %}1516With else block::17 18 {% for <item> in <seq> %}19 <data>20 {% else %}21 <data>22 {% endfor %}
added:test.html+53 added
added:test.py+7 added
1from jinja.environment import Environment23e = Environment()45def test(x):6 for pos, token, data in e.lexer.tokenize(x):7 print '%-8d%-30r%-40r' % (pos, token, data)