[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
Provenance
- Commit
92f572f- Tree
ebc7329- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>
18 files changed+1824 added−0 removed
added:jinja/translators/__init__.py+11 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.translators4+ ~~~~~~~~~~~~~~~~~5+6+ The submodules of this module provide translators for the jinja ast7+ which basically just is the python ast with a few more nodes.8+9+ :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+ ~~~~~~~~~~~~~~~~~~~~~~~~5+6+ This module translates a jinja ast into python code.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from compiler import ast12+from jinja import nodes13+14+15+class PythonTranslator(object):16+ """17+ Pass this translator a ast tree to get valid python code.18+ """19+20+ def __init__(self, environment, node):21+ self.environment = environment22+ self.node = node23+ self.indention = 024+ self.last_pos = 025+26+ 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+ }57+58+ def indent(self, text):59+ """60+ Indent the current text.61+ """62+ return (' ' * (self.indention * 4)) + text63+64+ 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 out73+74+ # -- jinja nodes75+76+ 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)86+87+ 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)114+115+ 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)132+133+ 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))139+140+ 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)146+147+ # -- python nodes148+149+ def handle_name(self, node):150+ """151+ Handle name assignments and name retreivement.152+ """153+ return 'context[%r]' % node.name154+155+ 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)165+166+ def handle_const(self, node):167+ """168+ Constant values in expressions.169+ """170+ return repr(node.value)171+172+ 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+ )184+185+ 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+ )193+194+ 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])199+200+ 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+ )208+209+ 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+ )232+233+ 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+ )241+242+ 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+ )250+251+ 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+ )259+260+ 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+ )268+269+ 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+ )277+278+ def handle_unary_sub(self, node):279+ """280+ Make a number negative.281+ """282+ return '(-%s)' % self.handle_node(node.expr)283+284+ 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+ )292+293+ 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+ ])303+304+ 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+ ])311+312+ 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+ ])319+320+ 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+ ])327+328+ def handle_not(self, node):329+ """330+ handle not operator.331+ """332+ return 'not %s' % self.handle_node(node.expr)333+334+ 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)345+346+347+def 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :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+ ~~~~~~~~~5+6+ Advance Syntax Tree for jinja.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+class Node(object):13+ """14+ Baseclass of all nodes. For instance checking.15+ """16+ __slots__ = ()17+18+ def __init__(self):19+ raise TypeError('cannot create %r instances' %20+ self.__class__.__name__)21+22+23+class Expression(list, Node):24+ """25+ Node that helds childnodes. Normally just used temporary.26+ """27+ __slots__ = ()28+29+ def __init__(self, *args, **kwargs):30+ super(Expression, self).__init__(*args, **kwargs)31+32+ def __repr__(self):33+ return 'Expression(%s)' % list.__repr__(self)34+35+36+class 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',)43+44+ def __init__(self, pos, comment):45+ self.pos = pos46+ self.comment = comment47+48+ def __repr__(self):49+ return 'Comment(%r, %r)' % (self.pos, self.comment)50+51+52+class Page(Node):53+ """54+ Node that helds all root nodes.55+ """56+ __slots__ = ('filename', 'nodes')57+58+ def __init__(self, filename, nodes):59+ self.filename = filename60+ self.nodes = nodes61+62+ def __repr__(self):63+ return 'Page(%r, %r)' % (64+ self.filename,65+ self.nodes66+ )67+68+69+class Variable(Node):70+ """71+ Node for variables72+ """73+ __slots__ = ('pos', 'expression')74+75+ def __init__(self, pos, expression):76+ self.pos = pos77+ self.expression = expression78+79+ def __repr__(self):80+ return 'Variable(%r)' % self.expression81+82+83+class Data(Node):84+ """85+ Node for data outside of tags.86+ """87+ __slots__ = ('pos', 'data')88+89+ def __init__(self, pos, data):90+ self.pos = pos91+ self.data = data92+93+ def __repr__(self):94+ return 'Data(%d, %r)' % (self.pos, self.data)95+96+97+class Name(Node):98+ """99+ Node for names.100+ """101+ __slots__ = ('pos', 'data')102+103+ def __init__(self, pos, data):104+ self.pos = pos105+ self.data = data106+107+ 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+ ~~~~~~~~~~~~~~~~~~~5+6+ Module that helds several data types used in the template engine.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+# python2.3 compatibility. do not use this method for anything else13+# then context reversing.14+try:15+ _reversed = reversed16+except NameError:17+ def _reversed(c):18+ return c[::-1]19+20+21+class UndefinedType(object):22+ """23+ An object that does not exist.24+ """25+26+ def __init__(self):27+ try:28+ Undefined29+ except NameError:30+ pass31+ else:32+ raise TypeError('cannot create %r instances' %33+ self.__class__.__name__)34+35+ def __getitem__(self, arg):36+ return self37+38+ def __iter__(self):39+ return iter(int, 0)40+41+ def __getattr__(self, arg):42+ return self43+44+ def __nonzero__(self):45+ return False46+47+ def __len__(self):48+ return 049+50+ def __str__(self):51+ return ''52+53+ def __unicode__(self):54+ return u''55+56+ def __int__(self):57+ return 058+59+ def __float__(self):60+ return 161+62+63+Undefined = UndefinedType()64+65+66+class Context(object):67+ """68+ Dict like object.69+ """70+71+ __slots__ = ('stack')72+73+ 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, {}]88+89+ def pop(self):90+ if len(self._stack) <= 2:91+ raise ValueError('cannot pop initial layer')92+ return self._stack.pop()93+94+ def push(self, data=None):95+ self._stack.append(data or {})96+97+ def __getitem__(self, name):98+ for d in _reversed(self._stack):99+ if name in d:100+ return d[name]101+ return Undefined102+103+ def __setitem__(self, name, value):104+ self._stack[-1][name] = value105+106+ def __delitem__(self, name):107+ if name in self._stack[-1]:108+ del self._stack[-1][name]109+110+ 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)116+117+118+class TokenStream(object):119+ """120+ A token stream works like a normal generator just that121+ it supports pushing tokens back to the stream.122+ """123+124+ def __init__(self, generator):125+ self._generator = generator126+ self._pushed = []127+ self.last = (0, 'initial', '')128+129+ def __iter__(self):130+ return self131+132+ 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 True141+142+ eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)143+144+ 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 rv152+153+ def look(self):154+ """Pop and push a token, return it."""155+ token = self.next()156+ self.push(*token)157+ return token158+159+ 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')172+173+ 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+ ~~~~~~~~~~~~~~5+6+ Jinja default filters and tags.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+13+DEFAULT_TAGS = {}14+15+DEFAULT_FILTERS = {}added:jinja/environment.py+86 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.environment4+ ~~~~~~~~~~~~~~~~~5+6+ Provides a class that holds runtime and parsing time options.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from jinja.lexer import Lexer12+from jinja.parser import Parser13+from jinja.exceptions import TagNotFound, FilterNotFound14+from jinja.defaults import DEFAULT_TAGS, DEFAULT_FILTERS15+16+17+class Environment(object):18+ """19+ The jinja environment.20+ """21+22+ 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):34+35+ # 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_string42+43+ # 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()49+50+ # create lexer51+ self.lexer = Lexer(self)52+53+ 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()57+58+ 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]66+67+ 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]75+76+ 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+ ~~~~~~~~~~~~~~~~5+6+ Jinja exceptions.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+13+class TemplateError(RuntimeError):14+ pass15+16+17+class TagNotFound(KeyError, TemplateError):18+ """19+ The parser looked for a specific tag in the tag library but was unable to find20+ one.21+ """22+23+ def __init__(self, tagname):24+ super(TagNotFound, self).__init__('The tag %r does not exist.' % tagname)25+ self.tagname = tagname26+27+28+class FilterNotFound(KeyError, TemplateError):29+ """30+ The template engine looked for a filter but was unable to find it.31+ """32+33+ def __init__(self, filtername):34+ super(FilterNotFound, self).__init__('The filter %r does not exist.' % filtername)35+ self.filtername = filtername36+37+38+class TemplateSyntaxError(SyntaxError, TemplateError):39+ """40+ Raised to tell the user that there is a problem with the template.41+ """42+43+ def __init__(self, message, pos):44+ super(TemplateSyntaxError, self).__init__(message)45+ self.pos = pos46+47+48+class TemplateRuntimeError(TemplateError):49+ """50+ Raised by the template engine if a tag encountered an error when51+ rendering.52+ """53+54+ def __init__(self, message, pos):55+ super(TemplateRuntimeError, self).__init__(message)56+ self.pos = posadded:jinja/filters.py+203 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.filters4+ ~~~~~~~~~~~~~5+6+ Bundled jinja filters.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+13+def 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 decorator26+27+28+def do_replace(s, old, new, count=None):29+ """30+ {{ s|replace(old, new, count=None) }}31+32+ 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)39+do_replace = stringfilter(do_replace)40+41+42+def do_upper(s):43+ """44+ {{ s|upper }}45+46+ Return a copy of s converted to uppercase.47+ """48+ return s.upper()49+do_upper = stringfilter(do_upper)50+51+52+def do_lower(s):53+ """54+ {{ s|lower }}55+56+ Return a copy of s converted to lowercase.57+ """58+ return s.lower()59+do_lower = stringfilter(do_lower)60+61+62+def do_escape(s, attribute=False):63+ """64+ {{ s|escape(attribute) }}65+66+ XML escape &, <, and > in a string of data. If attribute is67+ True it also converts ``"`` to ``"``68+ """69+ s = s.replace("&", "&").replace("<", "<").replace(">", ">")70+ if attribute:71+ s = s.replace('"', """)72+ return s73+do_escape = stringfilter(do_escape)74+75+76+def do_addslashes(s):77+ """78+ {{ s|addslashes }}79+80+ Adds slashes to s.81+ """82+ return s.encode('utf-8').encode('string-escape').decode('utf-8')83+do_addslashes = stringfilter(do_addslashes)84+85+86+def do_capitalize(s):87+ """88+ {{ s|capitalize }}89+90+ Return a copy of the string s with only its first character91+ capitalized.92+ """93+ return s.capitalize()94+do_capitalize = stringfilter(do_capitalize)95+96+97+def do_title(s):98+ """99+ {{ s|title }}100+101+ Return a titlecased version of s, i.e. words start with uppercase102+ characters, all remaining cased characters have lowercase.103+ """104+ return s.title()105+do_title = stringfilter(do_title)106+107+108+def do_default(default_value=u''):109+ """110+ {{ s|default(default_value='') }}111+112+ 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_value116+117+118+def do_join(d=u''):119+ """120+ {{ sequence|join(d='') }}121+122+ 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 wrapped130+131+132+def do_count():133+ """134+ {{ var|count }}135+136+ 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 wrapped152+153+154+def do_odd():155+ """156+ {{ var|odd }}157+158+ Return true if the variable is odd.159+ """160+ return lambda e, c, v: v % 2 == 1161+162+163+def do_even():164+ """165+ {{ var|even }}166+167+ Return true of the variable is even.168+ """169+ return lambda e, c, v: v % 2 == 0170+171+172+def do_reversed():173+ """174+ {{ var|reversed }}175+176+ 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 wrapped186+187+188+FILTERS = {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+"""6+import re7+from jinja.datastructure import TokenStream8+from jinja.exceptions import TemplateSyntaxError9+10+11+# static regular expressions12+whitespace_re = re.compile(r'\s+(?m)')13+name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*[!?]?')14+string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"15+ r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')16+number_re = re.compile(r'\d+(\.\d+)*')17+18+operator_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+]))28+29+30+class Failure(object):31+ """32+ Class that raises a `TemplateSyntaxError` if called.33+ Used by the `Lexer` to specify known errors.34+ """35+36+ def __init__(self, message, cls=TemplateSyntaxError):37+ self.message = message38+ self.error_class = cls39+40+ def __call__(self, position):41+ raise self.error_class(self.message, position)42+43+44+class 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+ """49+50+ def __init__(self, environment):51+ # shortcuts52+ c = lambda x: re.compile(x, re.M | re.S)53+ e = re.escape54+55+ # 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+ ]63+64+ # 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+ }89+90+ 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))98+99+ 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)110+111+ 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+ ~~~~~~~~~~~5+6+ Additional nodes for jinja. Look like nodes from the ast.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from compiler.ast import Node12+13+14+class Text(Node):15+ """16+ Node that represents normal text.17+ """18+19+ def __init__(self, pos, text):20+ self.pos = pos21+ self.text = text22+23+ def __repr__(self):24+ return 'Text(%r)' % (self.text,)25+26+27+class NodeList(list, Node):28+ """29+ A node that stores multiple childnodes.30+ """31+32+ def __init__(self, pos, data=None):33+ self.pos = pos34+ list.__init__(self, data or ())35+36+ def __repr__(self):37+ return 'NodeList(%s)' % list.__repr__(self)38+39+40+class ForLoop(Node):41+ """42+ A node that represents a for loop43+ """44+45+ def __init__(self, pos, item, seq, body, else_):46+ self.pos = pos47+ self.item = item48+ self.seq = seq49+ self.body = body50+ self.else_ = else_51+52+ def __repr__(self):53+ return 'ForLoop(%r, %r, %r, %r)' % (54+ self.item,55+ self.seq,56+ self.body,57+ self.else_58+ )59+60+61+class IfCondition(Node):62+ """63+ A node that represents an if condition.64+ """65+66+ def __init__(self, pos, test, body, else_):67+ self.pos = pos68+ self.test = test69+ self.body = body70+ self.else_ = else_71+72+ def __repr__(self):73+ return 'IfCondition(%r, %r, %r)' % (74+ self.test,75+ self.body,76+ self.else_77+ )78+79+80+class Print(Node):81+ """82+ A node that represents variable tags and print calls83+ """84+85+ def __init__(self, pos, variable):86+ self.pos = pos87+ self.variable = variable88+89+ def __repr__(self):90+ return 'Print(%r)' % (self.variable,)added:jinja/parser.py+219 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.parser4+ ~~~~~~~~~~~~5+6+ Implements the template parser.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import re12+from compiler import ast, parse13+from jinja import nodes14+from jinja.datastructure import TokenStream15+from jinja.exceptions import TemplateSyntaxError16+17+18+# callback functions for the subparse method19+end_of_block = lambda p, t, d: t == 'block_end'20+end_of_variable = lambda p, t, d: t == 'variable_end'21+switch_for = lambda p, t, d: t == 'name' and d in ('else', 'endfor')22+end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'23+switch_if = lambda p, t, d: t == 'name' and d in ('else', 'endif')24+end_of_if = lambda p, t, d: t == 'name' and d == 'endif'25+26+27+class Parser(object):28+ """29+ The template parser class.30+31+ Transforms sourcecode into an abstract syntax tree::32+33+ >>> 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+ """43+44+ 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 = False52+53+ self.directives = {54+ 'for': self.handle_for_directive,55+ 'if': self.handle_if_directive,56+ 'print': self.handle_print_directive57+ }58+59+ 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)65+66+ # 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()73+74+ return nodes.ForLoop(pos, ast.assign, ast.list, body, else_)75+76+ 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)82+83+ # 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()90+91+ return nodes.IfCondition(pos, ast.tests[0][0], body, else_)92+93+ 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])107+108+ 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]127+128+ def parse(self):129+ """130+ Parse the template and return a nodelist.131+ """132+ return self.subparse(None)133+134+ 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.140+141+ The test function is only called for the first token after a142+ block tag. Variable tags are *not* aliases for {% print %} in143+ that case.144+145+ 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 result152+153+ 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))161+162+ # 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)170+171+ # first token *must* be a name token172+ if token != 'name':173+ raise TemplateSyntaxError('unexpected %r token' % token, pos)174+175+ # 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()181+182+ # 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)190+191+ # 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))196+197+ # so this should be unreachable code198+ else:199+ raise AssertionError('unexpected token %r' % token)200+201+ # 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()205+206+ 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
1+source index.html::2+3+ {% page extends='layout.html', defaultfilter='autoescape',4+ charset='utf-8' %}5+6+ {% 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 %}20+21+source layout.html::22+23+ {% 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>43+44+generated python code::45+46+ from jinja.runtime import Template, Markup47+48+ class Layer1Template(Template):49+50+ defaultfilter = 'autoescape'51+52+ def p_title(self):53+ yield Markup(u'My Webpage')54+55+ def p_footer(self):56+ yield Markup(u'\n Copyright 2007 by the Pocoo Team.\n ')57+58+ 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')73+74+ class Layer2Template(Layer1Template):75+76+ defaultfilter = 'autoescape'77+78+ def p_title(self):79+ yield Markup(u'Index | ')80+ for i in self.resolve('super.title'):81+ yield i82+83+ 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()98+99+ def get_template(context):100+ return Layer2Template(context)101+102+generated javascript code::103+104+ (function(c) {105+ var m = function(x) { return new Jinja.Markup(x) };106+107+ 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+ };127+128+ 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+ };149+150+ return function(context) {151+ return new Jinja.Template(context, l1, l2);152+ };153+ })();added:tests/run.py+15 added
1+from jinja import Environment, FileSystemLoader2+3+env = Environment(4+ loader=FileSystemLoader(['.'], suffix='')5+)6+env.filters['odd?'] = lambda c, x: x % 2 == 17+env.filters['even?'] = lambda x, x: x % 2 == 08+9+t = env.get_template('index.html')10+print 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061Jinja 1.0 Syntax================
<ul>{% for char in my_string|upper|replace(" ", "") %} <li>{{ loop.index }} - {{ char|e }}</li>{% endfor %}</ul>
{{ variable|strip(" ")|escape|replace("a", "b") }}
{% if item == 42 %} ...{% endif %}
{% if item|odd? %} applies the odd? filter which returns true if the item in is odd.{% endif %}
{{ item|e(true) }} -- escape the variable for attributes
<ul>{% for item in seq %} <li>{{ item.current|e }} {% if item.items %}<ul>{% recurse item.items %}</ul>{% endif %} </li>{% endfor %}</ul>
How a Filter Looks Like=======================
def replace(search, repl): def wrapped(env, value): return env.to_unicode(value).replace(search, repl) return wrapped
def escape(attr=False): def wrapped(env, value): return cgi.escape(env.to_unicode(value), attr) return wrapped
def odd(): return lambda env, value: value % 2 == 1odd.__name__ = 'odd?'
@stringfilterdef replace(value, search, repl): return value.replace(search, repl)
def stringfilter(f): def decorator(*args): def wrapped(env, value): return f(env.to_unicode(value), *args) return wrapped return decoratoradded:syntax.txt+22 added
1+For Loops2+---------3+4+Simple Syntax::5+6+ {% for <item> in <seq> %}7+ <data>8+ {% endfor %}9+10+Item Unpacking::11+12+ {% for <item1>, <item2> in <seq> %}13+ <data>14+ {% endfor %}15+16+With else block::17+ 18+ {% for <item> in <seq> %}19+ <data>20+ {% else %}21+ <data>22+ {% endfor %}added:test.html+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{% block "page_title" %}Untitled{% endblock %} | My Webpage</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="screen.css" type="text/css" media="screen" /> <link rel="stylesheet" href="print.css" type="text/css" media="print" /> {% block html_head %}{% endblock %} </head> <body> <div id="header"> <h1>My Webpage</h1> <ul id="navigation"> {% for item in page_navigation %} <li><a href="{{ item.url|e }}"{% if item.active %} class="active"{% endif %}>{{ item.caption|e }}</a></li> {% endfor %} </ul> </div> <div id="body"> {% block body %} content goes here. {% endblock %} </div> <div id="sidebar"> <h2>Who is online?</h2> <ul> {% for user in online_users %} <li class="row_{% cycle 'even', 'odd' %}"><a href="{{ user.url|e }}">{{ user.username|e }}</a></li> {% endfor %} </ul> <h2>Sitemap</h2> {% macro draw_sitemap(items) %} <ul> {% for item in items %} <li>{{ item.name|e }}{% if item.items %}{{ draw_sitemap(item.items) }}{% endif %}</li> {% endfor %} </ul> {% endmacro %} {{ draw_sitemap(sitemap) }} <!-- alternative solution --> <ul> {% for item in items %} <li>{{ item.name|e }}{% if item.items %}<ul>{% recurse item.items %}</ul>{% endif %}</li> {% endfor %} </ul> </div> <div id="footer"> © Copyrigh by yourself. </div> </body></html>added:test.py+7 added
1+from jinja.environment import Environment2+3+e = Environment()4+5+def test(x):6+ for pos, token, data in e.lexer.tokenize(x):7+ print '%-8d%-30r%-40r' % (pos, token, data)