[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
Provenance
- Commit
9997f96- Tree
c68037d- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d874fbe
20 files changed+420 added−433 removed
modified:jinja/translators/__init__.py+19 added
7 unmodified lines8 9 :copyright: 2006 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12+13+14+class Translator(object):15+ """16+ Base class of all translators.17+ """18+19+ 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.26+27+ This is a static function.28+ """29+ pass30+ process = staticmethod(process)modified:jinja/translators/python.py+92 added-28 removed
9 unmodified lines10 """11 from compiler import ast12 from jinja import nodes13 from jinja.parser import Parser14+from jinja.datastructure import Context15 from jinja.exceptions import TemplateSyntaxError16+from jinja.translators import Translator17 18 17-class PythonTranslator(object):19+class Template(object):20 """21+ Represents a finished template.22+ """23+24+ def __init__(self, environment, generate_func):25+ self.environment = environment26+ self.generate_func = generate_func27+28+ 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)36+37+38+class PythonTranslator(Translator):39+ """40 Pass this translator a ast tree to get valid python code.41 """42 43 def __init__(self, environment, node):16 unmodified lines60 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 lines99 self.unsupported.update({100 ast.GenExpr: 'generator expressions'101 })102 81- self.reset()103+ # -- public methods104 105+ 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)112+113+ # -- private methods114+115 def indent(self, text):116 """117 Indent the current text.118 """16 unmodified lines135 # -- jinja nodes136 137 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.142+143+ 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 = tmpl156 157+ 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))167+168+ return '\n'.join(lines)169+170 def handle_template_text(self, node):171 """172 Handle data around nodes.173 """135 unmodified lines309 buf.append(self.indent('context[%r] = macro' % node.name))310 311 return '\n'.join(buf)312 313+ 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+ ))325+326+ buf = []327+ write = lambda x: buf.append(self.indent(x))328+329+ 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)338+339 # -- python nodes340 341 def handle_name(self, node):342 """272 unmodified lines615 args.append(self.handle_node(n))616 return '[%s]' % ':'.join(args)617 618 def reset(self):535- self.indention = 1619+ self.indention = 0620 self.last_cycle_id = 0621 622 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)546-547-548-def translate(environment, node):549- """550- Do the translation to python.551- """552- return PythonTranslator(environment, node).translate()553-554-555-def 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 lines6 :copyright: 2006 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 from jinja.environment import Environment10-from jinja.template import Template10+from jinja.loaders import FileSystemLoader11 12-__all__ = ['Environment', 'Template']12+__all__ = ['Environment', 'FileSystemLoader']modified:jinja/datastructure.py+30 added-4 removed
62 unmodified lines63 64 Undefined = UndefinedType()65 66 67+class Deferred(object):68+ """69+ Object marking an deferred value. Deferred objects are70+ objects that are called first access in the context.71+ """72+73+ def __init__(self, factory):74+ self.factory = factory75+76+ def __call__(self, context, name):77+ return self.factory(context, name)78+79+80 class Context(object):81 """82 Dict like object.83 """6 unmodified lines90 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._stack96 97 def pop(self):98 if len(self._stack) <= 2:99 raise ValueError('cannot pop initial layer')4 unmodified lines104 def push(self, data=None):105 self._stack.append(data or {})106 self.current = self._stack[-1]107 108+ 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 result117+118 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 Undefined129 130 def __setitem__(self, name, value):131 self._stack[-1][name] = value86 unmodified lines218 219 def __init__(self, generator):220 self._generator = generator221 self._pushed = []196- self.last = (0, 'initial', '')222+ self.last = (1, 'initial', '')223 224 def __iter__(self):225 return self226 44 unmodified linesmodified:jinja/defaults.py+5 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13+14+15+DEFAULT_NAMESPACE = {16+ 'range': xrange17+}modified:jinja/environment.py+22 added-3 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.lexer import Lexer12 from jinja.parser import Parser13+from jinja.loaders import LoaderWrapper14 from jinja.datastructure import Undefined15 from jinja.exceptions import FilterNotFound, TestNotFound15-from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS16+from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE17 18 19 class Environment(object):20 """8 unmodified lines29 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 lines46 # 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 tests52 53+ # global namespace54+ self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \55+ or namespace56+57 # create lexer58 self.lexer = Lexer(self)59 60+ 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__)66+67 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()71 72+ 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())77+78 def to_unicode(self, value):79 """80 Convert a value to unicode with the rules defined on the environment.81 """72 unmodified linesmodified:jinja/exceptions.py+9 added
30 unmodified lines31 def __init__(self, message):32 KeyError.__init__(self, message)33 34 35+class TemplateNotFound(IOError, TemplateError):36+ """37+ Raised if a template does not exist.38+ """39+40+ def __init__(self, message):41+ IOError.__init__(self, message)42+43+44 class TemplateSyntaxError(SyntaxError, TemplateError):45 """46 Raised to tell the user that there is a problem with the template.47 """15 unmodified linesadded:jinja/loaders.py+96 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.loaders4+ ~~~~~~~~~~~~~5+6+ Jinja loader classes.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import codecs13+from os import path14+from jinja.parser import Parser15+from jinja.translators.python import PythonTranslator16+from jinja.exceptions import TemplateNotFound17+18+19+def 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] != '.']))25+26+27+class LoaderWrapper(object):28+ """29+ Wraps a loader so that it's bound to an environment.30+ """31+32+ def __init__(self, environment, loader):33+ self.environment = environment34+ self.loader = loader35+36+ 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)41+42+ def parse(self, name, parent=None):43+ """44+ Retreive a template and parse it.45+ """46+ return self.loader.parse(self.environment, name, parent)47+48+ 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)55+56+57+class FileSystemLoader(object):58+ """59+ Loads templates from the filesystem::60+61+ from jinja import Environment, FileSystemLoader62+ e = Environment(loader=FileSystemLoader('templates/'))63+ """64+65+ 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 = {}70+71+ 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)81+82+ def parse(self, environment, name, parent):83+ source = self.get_source(environment, name, parent)84+ return Parser(environment, source, name).parse()85+86+ 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 rvmodified:jinja/nodes.py+57 added-6 removed
29 unmodified lines30 """31 jinja node.32 """33 34+ def get_items(self):35+ return []36+37 def getChildren(self):38 return self.get_items()39 40 def getChildNodes(self):24 unmodified lines65 def __init__(self, lineno, data=None):66 self.lineno = lineno67 list.__init__(self, data or ())68 66- getChildren = getChildNodes = lambda s: list(s)69+ getChildren = getChildNodes = lambda s: list(s) + s.get_items()70 71 def __repr__(self):72 return '%s(%s)' % (73 self.__class__.__name__,2 unmodified lines76 77 78 class Template(NodeList):79 """77- A template.80+ Node that represents a template.81 """82 80- 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)90 91+ def get_items(self):92+ result = self.blocks.values()93+ if self.extends is not None:94+ result.append(self.extends)95+ return result96 97+98 class ForLoop(Node):99 """100 A node that represents a for loop101 """98 unmodified lines200 self.name,201 self.arguments,202 self.body203 )204+205+206+class Block(Node):207+ """208+ A node that represents a block.209+ """210+211+ def __init__(self, lineno, name, body):212+ self.lineno = lineno213+ self.name = name214+ self.body = body215+216+ 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__)222+223+ def get_items(self):224+ return [self.name, self.body]225+226+ def __repr__(self):227+ return 'Block(%r, %r)' % (228+ self.name,229+ self.body230+ )231+232+233+class Extends(Node):234+ """235+ A node that represents the extends tag.236+ """237+238+ def __init__(self, lineno, template):239+ self.lineno = lineno240+ self.template = template241+242+ def __repr__(self):243+ return 'Extends(%r)' % self.templatemodified:jinja/parser.py+53 added-17 removed
22 unmodified lines23 end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'24 switch_if = lambda p, t, d: t == 'name' and d in ('else', 'elif', 'endif')25 end_of_if = lambda p, t, d: t == 'name' and d == 'endif'26 end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'27+end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'28 29 30 class Parser(object):31 """32 The template parser class.33 33- Transforms sourcecode into an abstract syntax tree::34-35- >>> 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 """36 37 def __init__(self, environment, source, filename=None):38 self.environment = environment1 unmodified line40 source = source.decode(environment.template_charset, 'ignore')41 self.source = source42 self.filename = filename43 self.tokenstream = environment.lexer.tokenize(source)53- self._parsed = False44 45+ self.extends = None46+ self.blocks = {}47+48 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 }57 58 def handle_for_directive(self, lineno, gen):59 """97 unmodified lines157 '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)160 161+ 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)176+177+ if block_name[2] in self.blocks:178+ raise TemplateSyntaxError('block %r defined twice' %179+ block_name[2], lineno)180+181+ 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 rv186+187+ 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])197+198 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 a8 unmodified lines210 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 result219 220 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)226 227 def subparse(self, test, drop_needle=False):228 """229 Helper function used to parse the sourcecode until the test49 unmodified lines279 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)287 288 # 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 linesdeleted:jinja/template.py-51 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja.template4- ~~~~~~~~~~~~~~5-6- Template class.7-8- :copyright: 2006 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-11-"""12-from jinja.nodes import Node13-from jinja.datastructure import Context14-from jinja.translators.python import parse_and_translate, translate15-16-17-def evaluate_source(source):18- """19- Evaluate a sourcecode and return the generate function.20- """21- ns = {}22- exec source in ns23- return ns['generate']24-25-26-class Template(object):27- """28- Represents a finished template.29- """30-31- 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 = None41-42- 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
1+from jinja import Environment, FileSystemLoader2+e = Environment(loader=FileSystemLoader('templates'))3+4+from jinja.parser import Parser5+from jinja.translators.python import PythonTranslator6+7+print PythonTranslator(e, e.loader.parse('index.html')).translate()deleted:tests/mockup.txt-153 removed
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- })();deleted:tests/run.py-15 removed
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-)deleted:syntax.html-61 removed
1-Jinja 1.0 Syntax2-================3-4-<ul>5-{% for char in my_string|upper|replace(" ", "") %}6- <li>{{ loop.index }} - {{ char|e }}</li>7-{% endfor %}8-</ul>9-10-{{ variable|strip(" ")|escape|replace("a", "b") }}11-12-{% if item == 42 %}13- ...14-{% endif %}15-16-{% if item|odd? %}17- applies the odd? filter which returns true if the18- item in is odd.19-{% endif %}20-21-{{ item|e(true) }} -- escape the variable for attributes22-23-<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>30-31-How a Filter Looks Like32-=======================33-34-def replace(search, repl):35- def wrapped(env, value):36- return env.to_unicode(value).replace(search, repl)37- return wrapped38-39-40-def escape(attr=False):41- def wrapped(env, value):42- return cgi.escape(env.to_unicode(value), attr)43- return wrapped44-45-46-def odd():47- return lambda env, value: value % 2 == 148-odd.__name__ = 'odd?'49-50-51-@stringfilter52-def replace(value, search, repl):53- return value.replace(search, repl)54-55-56-def stringfilter(f):57- def decorator(*args):58- def wrapped(env, value):59- return f(env.to_unicode(value), *args)60- return wrapped61- return decoratordeleted:syntax.txt-22 removed
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 %}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- © Copyrigh by yourself.51- </div>52- </body>53-</html>deleted:test.py-18 removed
1-from jinja.environment import Environment2-3-e = Environment()4-5-def test_lexer(x):6- for pos, token, data in e.lexer.tokenize(x):7- print '%-8d%-30r%-40r' % (pos, token, data)8-9-10-def test_parser(x):11- from jinja.parser import Parser12- from jinja.translators.python import translate13- print translate(e, Parser(e, x).parse())14-15-16-def load_template(x):17- from jinja.template import Template18- return Template(e, x)