Skip to content
Myr

[svn] checked in today's jinja changes. implemented template loading and inheritance

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 d874fbe · Browse files · 20 files+420 added−433 removed
This commit

State

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

Diff stats

20 files+420 added−433 removed

  • tests:+35 added−168 removed
  • other:+385 added−265 removed

20 files+420 added−433 removed

modified:jinja/translators/__init__.py+19 added
7 unmodified lines
89 :copyright: 2006 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""121314class Translator(object):15 """16 Base class of all translators.17 """1819 def process(environment, tree):20 """21 Process the given ast with the rules defined in22 environment and return a translated version of it.23 The translated object can be anything. The python24 translator for example outputs Template instances,25 a javascript translator would probably output strings.2627 This is a static function.28 """29 pass30 process = staticmethod(process)
modified:jinja/translators/python.py+92 added-28 removed
9 unmodified lines
10"""11from compiler import ast12from jinja import nodes13from jinja.parser import Parser14from jinja.datastructure import Context15from jinja.exceptions import TemplateSyntaxError16from jinja.translators import Translator171817class PythonTranslator(object):19class Template(object):20 """21 Represents a finished template.22 """2324 def __init__(self, environment, generate_func):25 self.environment = environment26 self.generate_func = generate_func2728 def render(self, *args, **kwargs):29 """30 Render a template.31 """32 result = []33 ctx = Context(self.environment, *args, **kwargs)34 self.generate_func(ctx, result.append)35 return u''.join(result)363738class PythonTranslator(Translator):39 """40 Pass this translator a ast tree to get valid python code.41 """4243 def __init__(self, environment, node):
16 unmodified lines
60 nodes.IfCondition: self.handle_if_condition,61 nodes.Cycle: self.handle_cycle,62 nodes.Print: self.handle_print,63 nodes.Macro: self.handle_macro,64 nodes.Block: self.handle_block,65 # used python nodes66 ast.Name: self.handle_name,67 ast.AssName: self.handle_name,68 ast.Compare: self.handle_compare,
30 unmodified lines
99 self.unsupported.update({100 ast.GenExpr: 'generator expressions'101 })10281 self.reset()103 # -- public methods104105 def process(environment, node):106 translator = PythonTranslator(environment, node)107 source = translator.translate()108 ns = {}109 exec source in ns110 return Template(environment, ns['generate'])111 process = staticmethod(process)112113 # -- private methods114115 def indent(self, text):116 """117 Indent the current text.118 """
16 unmodified lines
135 # -- jinja nodes136137 def handle_template(self, node):138 """107 Handle a template node. Basically do nothing but calling the108 handle_node_list function.139 Handle the overall template node. This node is the first node and ensures140 that we get the bootstrapping code. It also knows about inheritance141 information. It only occours as outer node, never in the tree itself.142143 Nevertheless we call indent here to simplify futur changes.144 """110 return self.handle_node_list(node)145 # if there is a parent template we parse the parent template and146 # update the blocks there. Once this is done we drop the current147 # template in favor of the new one. Do that until we found the148 # root template.149 while node.extends is not None:150 tmpl = self.environment.loader.parse(node.extends.template,151 node.filename)152 for block in tmpl.blocks.itervalues():153 if block.name in node.blocks:154 block.replace(node.blocks[block.name])155 node = tmpl156157 lines = [self.indent(158 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'159 'def generate(context, write, write_var=None):\n'160 ' environment = context.environment\n'161 ' if write_var is None:\n'162 ' write_var = lambda x: write(environment.finish_var(x))'163 )]164 write = lambda x: lines.append(self.indent(x))165 self.indention += 1166 lines.append(self.handle_node_list(node))167168 return '\n'.join(lines)169170 def handle_template_text(self, node):171 """172 Handle data around nodes.173 """
135 unmodified lines
309 buf.append(self.indent('context[%r] = macro' % node.name))310311 return '\n'.join(buf)312313 def handle_block(self, node):314 """315 Handle blocks in the sourcecode. We only use them to316 call the current block implementation that is stored somewhere317 else.318 """319 rv = self.handle_node(node.body)320 if not rv:321 return self.indent('# empty block from %r, line %s' % (322 node.filename or '?',323 node.lineno324 ))325326 buf = []327 write = lambda x: buf.append(self.indent(x))328329 write('# block from %r, line %s' % (330 node.filename or '?',331 node.lineno332 ))333 write('context.push()')334 buf.append(self.handle_node(node.body))335 write('context.pop()')336 buf.append(self.indent('# end of block'))337 return '\n'.join(buf)338339 # -- python nodes340341 def handle_name(self, node):342 """
272 unmodified lines
615 args.append(self.handle_node(n))616 return '[%s]' % ':'.join(args)617618 def reset(self):535 self.indention = 1619 self.indention = 0620 self.last_cycle_id = 0621622 def translate(self):539 return (540 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'541 'def generate(context, write, write_var=None):\n'542 ' environment = context.environment\n'543 ' if write_var is None:\n'544 ' write_var = lambda x: write(environment.finish_var(x))\n'545 ) + self.handle_node(self.node)546547548def translate(environment, node):549 """550 Do the translation to python.551 """552 return PythonTranslator(environment, node).translate()553554555def parse_and_translate(environment, source, filename=None):556 """557 Parse sourcecode and translate it to python558 """559 node = Parser(environment, source, filename).parse()560 return PythonTranslator(environment, node).translate()623 self.reset()624 return self.handle_node(self.node)
modified:jinja/__init__.py+2 added-2 removed
5 unmodified lines
6 :copyright: 2006 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja.environment import Environment10from jinja.template import Template10from jinja.loaders import FileSystemLoader1112__all__ = ['Environment', 'Template']12__all__ = ['Environment', 'FileSystemLoader']
modified:jinja/datastructure.py+30 added-4 removed
62 unmodified lines
6364Undefined = UndefinedType()656667class Deferred(object):68 """69 Object marking an deferred value. Deferred objects are70 objects that are called first access in the context.71 """7273 def __init__(self, factory):74 self.factory = factory7576 def __call__(self, context, name):77 return self.factory(context, name)787980class Context(object):81 """82 Dict like object.83 """
6 unmodified lines
90 except:91 raise TypeError('%r requires environment as first argument. '92 'The rest of the arguments are forwarded to '93 'the default dict constructor.')81 self._stack = [initial, {}]82 self.globals, self.current = self._stack94 self._stack = [self.environment.globals, initial, {}]95 self.globals, _, self.current = self._stack9697 def pop(self):98 if len(self._stack) <= 2:99 raise ValueError('cannot pop initial layer')
4 unmodified lines
104 def push(self, data=None):105 self._stack.append(data or {})106 self.current = self._stack[-1]107108 def to_dict(self):109 """110 Convert the context into a dict. This skips the globals.111 """112 result = {}113 for layer in self._stack[1:]:114 for key, value in layer.iteritems():115 result[key] = value116 return result117118 def __getitem__(self, name):119 # don't give access to jinja internal variables120 if name.startswith('::'):121 return Undefined122 for d in _reversed(self._stack):123 if name in d:101 return d[name]124 rv = d[name]125 if isinstance(rv, Deferred):126 d[name] = rv = rv(self, name)127 return rv128 return Undefined129130 def __setitem__(self, name, value):131 self._stack[-1][name] = value
86 unmodified lines
218219 def __init__(self, generator):220 self._generator = generator221 self._pushed = []196 self.last = (0, 'initial', '')222 self.last = (1, 'initial', '')223224 def __iter__(self):225 return self226
44 unmodified lines
modified:jinja/defaults.py+5 added
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS131415DEFAULT_NAMESPACE = {16 'range': xrange17}
modified:jinja/environment.py+22 added-3 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja.lexer import Lexer12from jinja.parser import Parser13from jinja.loaders import LoaderWrapper14from jinja.datastructure import Undefined15from jinja.exceptions import FilterNotFound, TestNotFound15from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS16from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE171819class Environment(object):20 """
8 unmodified lines
29 comment_start_string='{#',30 comment_end_string='#}',31 template_charset='utf-8',32 charset='utf-8',33 namespace=None,34 loader=None,35 filters=None,36 tests=None):37
8 unmodified lines
46 # other stuff47 self.template_charset = template_charset48 self.charset = charset49 self.loader = loader48 self.filters = filters or DEFAULT_FILTERS.copy()49 self.tests = filters or DEFAULT_TESTS.copy()50 self.filters = filters is None and DEFAULT_FILTERS.copy() or filters51 self.tests = tests is None and DEFAULT_TESTS.copy() or tests5253 # global namespace54 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \55 or namespace5657 # create lexer58 self.lexer = Lexer(self)5960 def loader(self, value):61 """62 Get or set the template loader.63 """64 self._loader = LoaderWrapper(self, value)65 loader = property(lambda s: s._loader, loader, loader.__doc__)6667 def parse(self, source):68 """Function that creates a new parser and parses the source."""69 parser = Parser(self, source)70 return parser.parse_page()7172 def from_string(self, source):73 """Load a template from a string."""74 from jinja.parser import Parser75 from jinja.translators.python import PythonTranslator76 return PythonTranslator.process(self, Parser(self, source).parse())7778 def to_unicode(self, value):79 """80 Convert a value to unicode with the rules defined on the environment.81 """
72 unmodified lines
modified:jinja/exceptions.py+9 added
30 unmodified lines
31 def __init__(self, message):32 KeyError.__init__(self, message)333435class TemplateNotFound(IOError, TemplateError):36 """37 Raised if a template does not exist.38 """3940 def __init__(self, message):41 IOError.__init__(self, message)424344class TemplateSyntaxError(SyntaxError, TemplateError):45 """46 Raised to tell the user that there is a problem with the template.47 """
15 unmodified lines
added:jinja/loaders.py+96 added
1# -*- coding: utf-8 -*-2"""3 jinja.loaders4 ~~~~~~~~~~~~~56 Jinja loader classes.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import codecs13from os import path14from jinja.parser import Parser15from jinja.translators.python import PythonTranslator16from jinja.exceptions import TemplateNotFound171819def get_template_filename(searchpath, name):20 """21 Return the filesystem filename wanted.22 """23 return path.join(searchpath, path.sep.join([p for p in name.split('/')24 if p and p[0] != '.']))252627class LoaderWrapper(object):28 """29 Wraps a loader so that it's bound to an environment.30 """3132 def __init__(self, environment, loader):33 self.environment = environment34 self.loader = loader3536 def get_source(self, name, parent=None):37 """38 Retrieve the sourcecode of a template.39 """40 return self.loader.get_source(self.environment, name, parent)4142 def parse(self, name, parent=None):43 """44 Retreive a template and parse it.45 """46 return self.loader.parse(self.environment, name, parent)4748 def load(self, name, translator=PythonTranslator):49 """50 Translate a template and return it. This must not necesarily51 be a template class. The javascript translator for example52 will just output a string with the translated code.53 """54 return self.loader.load(self.environment, name, translator)555657class FileSystemLoader(object):58 """59 Loads templates from the filesystem::6061 from jinja import Environment, FileSystemLoader62 e = Environment(loader=FileSystemLoader('templates/'))63 """6465 def __init__(self, searchpath, use_cache=False, cache_size=40):66 self.searchpath = searchpath67 self.use_cache = use_cache68 self.cache_size = cache_size69 self.cache = {}7071 def get_source(self, environment, name, parent):72 filename = get_template_filename(self.searchpath, name)73 if path.exists(filename):74 f = codecs.open(filename, 'r', environment.template_charset)75 try:76 return f.read()77 finally:78 f.close()79 else:80 raise TemplateNotFound(name)8182 def parse(self, environment, name, parent):83 source = self.get_source(environment, name, parent)84 return Parser(environment, source, name).parse()8586 def load(self, environment, name, translator):87 if self.use_cache:88 key = (name, translator)89 if key in self.cache:90 return self.cache[key]91 if len(self.cache) >= self.cache_size:92 self.cache.clear()93 rv = translator.process(environment, self.parse(environment, name, None))94 if self.use_cache:95 self.cache[key] = rv96 return rv
modified:jinja/nodes.py+57 added-6 removed
29 unmodified lines
30 """31 jinja node.32 """3334 def get_items(self):35 return []3637 def getChildren(self):38 return self.get_items()3940 def getChildNodes(self):
24 unmodified lines
65 def __init__(self, lineno, data=None):66 self.lineno = lineno67 list.__init__(self, data or ())6866 getChildren = getChildNodes = lambda s: list(s)69 getChildren = getChildNodes = lambda s: list(s) + s.get_items()7071 def __repr__(self):72 return '%s(%s)' % (73 self.__class__.__name__,
2 unmodified lines
767778class Template(NodeList):79 """77 A template.80 Node that represents a template.81 """8280 def __init__(self, filename, node):81 if node.__class__ is not NodeList:82 node = (node,)83 NodeList.__init__(self, 0, node)83 def __init__(self, filename, body, blocks, extends):84 if body.__class__ is not NodeList:85 body = (body,)86 NodeList.__init__(self, 0, body)87 self.blocks = blocks88 self.extends = extends89 set_filename(filename, self)9091 def get_items(self):92 result = self.blocks.values()93 if self.extends is not None:94 result.append(self.extends)95 return result969798class ForLoop(Node):99 """100 A node that represents a for loop101 """
98 unmodified lines
200 self.name,201 self.arguments,202 self.body203 )204205206class Block(Node):207 """208 A node that represents a block.209 """210211 def __init__(self, lineno, name, body):212 self.lineno = lineno213 self.name = name214 self.body = body215216 def replace(self, node):217 """218 Replace the current data with the data of another block node.219 """220 assert node.__class__ is Block221 self.__dict__.update(node.__dict__)222223 def get_items(self):224 return [self.name, self.body]225226 def __repr__(self):227 return 'Block(%r, %r)' % (228 self.name,229 self.body230 )231232233class Extends(Node):234 """235 A node that represents the extends tag.236 """237238 def __init__(self, lineno, template):239 self.lineno = lineno240 self.template = template241242 def __repr__(self):243 return 'Extends(%r)' % self.template
modified:jinja/parser.py+53 added-17 removed
22 unmodified lines
23end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'24switch_if = lambda p, t, d: t == 'name' and d in ('else', 'elif', 'endif')25end_of_if = lambda p, t, d: t == 'name' and d == 'endif'26end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'27end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'282930class Parser(object):31 """32 The template parser class.3333 Transforms sourcecode into an abstract syntax tree::3435 >>> parse("{% for item in seq|reversed %}{{ item }}{% endfor %}")36 Document(ForLoop(AssignName('item'), Filter(Name('seq'), Name('reversed')),37 Print('item'), None))38 >>> parse("{% if true %}foo{% else %}bar{% endif %}")39 Document(IfCondition(Name('true'), Data('foo'), Data('bar')))40 >>> parse("{% if false %}...{% elif 0 > 1 %}...{% else %}...{% endif %}")41 Document(IfCondition(Name('false'), Data('...'),42 IfCondition(Compare('>', Const(0), Const(1)),43 Data('...'), Data('...'))))34 Transforms sourcecode into an abstract syntax tree.35 """3637 def __init__(self, environment, source, filename=None):38 self.environment = environment
1 unmodified line
40 source = source.decode(environment.template_charset, 'ignore')41 self.source = source42 self.filename = filename43 self.tokenstream = environment.lexer.tokenize(source)53 self._parsed = False4445 self.extends = None46 self.blocks = {}4748 self.directives = {49 'for': self.handle_for_directive,50 'if': self.handle_if_directive,51 'cycle': self.handle_cycle_directive,52 'print': self.handle_print_directive,60 'macro': self.handle_macro_directive53 'macro': self.handle_macro_directive,54 'block': self.handle_block_directive,55 'extends': self.handle_extends_directive56 }5758 def handle_for_directive(self, lineno, gen):59 """
97 unmodified lines
157 'not allowed.', lineno)158 defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults159 return nodes.Macro(lineno, ast.name, zip(ast.argnames, defaults), body)160161 def handle_block_directive(self, lineno, gen):162 """163 Handle block directives used for inheritance.164 """165 tokens = list(gen)166 if not tokens:167 raise TemplateSyntaxError('block requires a name', lineno)168 block_name = tokens.pop(0)169 if block_name[1] != 'name':170 raise TemplateSyntaxError('expected \'name\', got %r' %171 block_name[1], lineno)172 if tokens:173 print tokens174 raise TemplateSyntaxError('block got too many arguments, '175 'requires one.', lineno)176177 if block_name[2] in self.blocks:178 raise TemplateSyntaxError('block %r defined twice' %179 block_name[2], lineno)180181 body = self.subparse(end_of_block_tag, True)182 self.close_remaining_block()183 rv = nodes.Block(lineno, block_name[2], body)184 self.blocks[block_name[2]] = rv185 return rv186187 def handle_extends_directive(self, lineno, gen):188 """189 Handle extends directive used for inheritance.190 """191 tokens = list(gen)192 if len(tokens) != 1 or tokens[0][1] != 'string':193 raise TemplateSyntaxError('extends requires a string', lineno)194 if self.extends is not None:195 raise TemplateSyntaxError('extends called twice', lineno)196 self.extends = nodes.Extends(lineno, tokens[0][2][1:-1])197198 def parse_python(self, lineno, gen, template='%s'):199 """200 Convert the passed generator into a flat string representing201 python sourcecode and return an ast node or raise a
8 unmodified lines
210 source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).encode('utf-8'))211 try:212 ast = parse(source, 'exec')213 except SyntaxError, e:182 raise TemplateSyntaxError(str(e), lineno + e.lineno - 1)214 raise TemplateSyntaxError('invalid syntax', lineno + e.lineno)215 assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % len(ast.node.nodes)216 result = ast.node.nodes[0]217 nodes.inc_lineno(lineno, result)218 return result219220 def parse(self):221 """190 Parse the template and return a Template.222 Parse the template and return a Template node.223 """224 body = self.subparse(None)192 return nodes.Template(self.filename, self.subparse(None))225 return nodes.Template(self.filename, body, self.blocks, self.extends)226227 def subparse(self, test, drop_needle=False):228 """229 Helper function used to parse the sourcecode until the test
49 unmodified lines
279 if data in self.directives:280 node = self.directives[data](lineno, gen)281 else:282 raise TemplateSyntaxError('unknown directive %r' % data, lineno)283 # some tags like the extends tag do not output nodes.284 # so just skip that.285 if node is not None:250 result.append(node)286 result.append(node)287288 # here the only token we should get is "data". all other289 # tokens just exist in block or variable sections. (if the290 # tokenizer is not brocken)
26 unmodified lines
deleted:jinja/template.py-51 removed
1# -*- coding: utf-8 -*-2"""3 jinja.template4 ~~~~~~~~~~~~~~56 Template class.78 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.1011"""12from jinja.nodes import Node13from jinja.datastructure import Context14from jinja.translators.python import parse_and_translate, translate151617def evaluate_source(source):18 """19 Evaluate a sourcecode and return the generate function.20 """21 ns = {}22 exec source in ns23 return ns['generate']242526class Template(object):27 """28 Represents a finished template.29 """3031 def __init__(self, environment, source):32 if isinstance(source, basestring):33 self.source = parse_and_translate(environment, source)34 elif isinstance(source, Node):35 self.source = translate(environment, source)36 else:37 raise TypeError('unsupported source type %r' %38 source.__class__.__name__)39 self.environment = environment40 self.generate_func = None4142 def render(self, *args, **kwargs):43 """44 Render a template.45 """46 if self.generate_func is None:47 self.generate_func = evaluate_source(self.source)48 result = []49 ctx = Context(self.environment, *args, **kwargs)50 self.generate_func(ctx, result.append)51 return u''.join(result)
added:tests/templates/index.html+5 added
1{% extends "layout.html" %}2{% block page_title %}Index{% endblock %}3{% block body %}4 This is the index page.5{% endblock %}
added:tests/templates/layout.html+23 added
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Frameset//EN"2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">3<html>4 <head>5 <title>{% block page_title %}Untitled{% endblock %} | My Webpage</title>6 {% block page_head %}{% endblock %}7 </head>8 <body>9 <div id="header">10 <h1>My Webpage</h1>11 <ul id="navigation">12 {% for item in navigation_items %}13 <li><a href="{{ item.url|escape }}">{{ item.caption|escape }}</a></li>14 {% endfor %}15 </ul>16 </div>17 <div id="body">18 {% block body %}19 content goes here.20 {% endblock %}21 </div>22 </body>23</html>
added:tests/inheritance.py+7 added
1from jinja import Environment, FileSystemLoader2e = Environment(loader=FileSystemLoader('templates'))34from jinja.parser import Parser5from jinja.translators.python import PythonTranslator67print PythonTranslator(e, e.loader.parse('index.html')).translate()
deleted:tests/mockup.txt-153 removed
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 })();
deleted:tests/run.py-15 removed
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)
deleted:syntax.html-61 removed
1Jinja 1.0 Syntax2================34<ul>5{% for char in my_string|upper|replace(" ", "") %}6 <li>{{ loop.index }} - {{ char|e }}</li>7{% endfor %}8</ul>910{{ variable|strip(" ")|escape|replace("a", "b") }}1112{% if item == 42 %}13 ...14{% endif %}1516{% if item|odd? %}17 applies the odd? filter which returns true if the18 item in is odd.19{% endif %}2021{{ item|e(true) }} -- escape the variable for attributes2223<ul>24{% for item in seq %}25 <li>{{ item.current|e }}26 {% if item.items %}<ul>{% recurse item.items %}</ul>{% endif %}27 </li>28{% endfor %}29</ul>3031How a Filter Looks Like32=======================3334def replace(search, repl):35 def wrapped(env, value):36 return env.to_unicode(value).replace(search, repl)37 return wrapped383940def escape(attr=False):41 def wrapped(env, value):42 return cgi.escape(env.to_unicode(value), attr)43 return wrapped444546def odd():47 return lambda env, value: value % 2 == 148odd.__name__ = 'odd?'495051@stringfilter52def replace(value, search, repl):53 return value.replace(search, repl)545556def stringfilter(f):57 def decorator(*args):58 def wrapped(env, value):59 return f(env.to_unicode(value), *args)60 return wrapped61 return decorator
deleted:syntax.txt-22 removed
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 %}
deleted:test.html-53 removed
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Frameset//EN"2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">3<html xmlns="http://www.w3.org/1999/xhtml">4 <head>5 <title>{% block "page_title" %}Untitled{% endblock %} | My Webpage</title>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />7 <link rel="stylesheet" href="screen.css" type="text/css" media="screen" />8 <link rel="stylesheet" href="print.css" type="text/css" media="print" />9 {% block html_head %}{% endblock %}10 </head>11 <body>12 <div id="header">13 <h1>My Webpage</h1>14 <ul id="navigation">15 {% for item in page_navigation %}16 <li><a href="{{ item.url|e }}"{% if item.active %}17 class="active"{% endif %}>{{ item.caption|e }}</a></li>18 {% endfor %}19 </ul>20 </div>21 <div id="body">22 {% block body %}23 content goes here.24 {% endblock %}25 </div>26 <div id="sidebar">27 <h2>Who is online?</h2>28 <ul>29 {% for user in online_users %}30 <li class="row_{% cycle 'even', 'odd' %}"><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>31 {% endfor %}32 </ul>33 <h2>Sitemap</h2>34 {% macro draw_sitemap(items) %}35 <ul>36 {% for item in items %}37 <li>{{ item.name|e }}{% if item.items %}{{ draw_sitemap(item.items) }}{% endif %}</li>38 {% endfor %}39 </ul>40 {% endmacro %}41 {{ draw_sitemap(sitemap) }}42 <!-- alternative solution -->43 <ul>44 {% for item in items %}45 <li>{{ item.name|e }}{% if item.items %}<ul>{% recurse item.items %}</ul>{% endif %}</li>46 {% endfor %}47 </ul>48 </div>49 <div id="footer">50 &copy; Copyrigh by yourself.51 </div>52 </body>53</html>
deleted:test.py-18 removed
1from jinja.environment import Environment23e = Environment()45def test_lexer(x):6 for pos, token, data in e.lexer.tokenize(x):7 print '%-8d%-30r%-40r' % (pos, token, data)8910def test_parser(x):11 from jinja.parser import Parser12 from jinja.translators.python import translate13 print translate(e, Parser(e, x).parse())141516def load_template(x):17 from jinja.template import Template18 return Template(e, x)