[svn] doc update, setup.py update, added turbogears plugin
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 37a8851 · Browse files · 21 files·+342 added−93 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
21 files+342 added−93 removed
- other:+342 added−93 removed
Provenance
- Commit
8ebf1f9- Tree
26ed85b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
37a8851
21 files changed+342 added−93 removed
added:docs/src/filters.txt+57 added
1+================2+Filter Functions3+================4+5+Filters are a powerful feature of Jinja taken from django which probably took6+it from UNIX. The idea is that you "pipe" a value through some filters to7+do something with it. For example convert it to upper case, escape it or8+replace a substring.9+10+Jinja comes with some builtin filters explained in the `designer documentation`_.11+12+Writing Filters13+===============14+15+A filter basically is a factory function. Thus a function that returns another16+function. We do this because filters can get an unlimited amount of position17+arguments and aditionally should gain access to the environment, context and18+piped value. A simple filter looks like this:19+20+.. sourcecode:: python21+22+ def do_join(d=u''):23+ def wrapped(env, context, value):24+ tmp = []25+ for item in value:26+ tmp.append(env.to_unicode(item))27+ return d.join(tmp)28+ return wrapped29+30+Now you have to register that filter on an environment:31+32+.. sourcecode:: python33+34+ env.filters['join'] = do_join35+36+In fact this filter is already bundled so you won't see any effect. But its37+should explain how such a filter looks like. The template designer can just38+trigger the outer code (eg: call do_join with or without arguments). The39+returned function is then processed by the jinja template engine once all40+filters are created.41+42+If you want to create filters that just operate on string (in fact unicode43+objects) you can use the `stringfilter` decorator:44+45+.. sourcecode:: python46+47+ from jinja.filters import stringfilter48+49+ @stringfilter50+ def do_strip(value):51+ return value.strip()52+53+The wrapped function is created internally by the decorator, any positional54+arguments are forwarded to the filter function. The first argument is always55+the value already converted into a string.56+57+.. _designer documentation: designerdoc.txtadded:docs/src/installation.txt+64 added
1+============2+Installation3+============4+5+Jinja requires at least Python 2.3 to work correctly.6+7+Installing a released version8+=============================9+10+As a Python egg (via easy_install)11+----------------------------------12+13+You can install the most recent Jinja version using `easy_install`_::14+15+ sudo easy_install Jinja16+17+This will install a Jinja egg in your Python installation's site-packages18+directory.19+20+21+From the tarball release22+-------------------------23+24+1. Download the most recent tarball from the `download page`_25+2. Unpack the tarball26+3. ``sudo python setup.py install``27+28+Note that the last command will automatically download and install29+`setuptools`_ if you don't already have it installed. This requires a working30+internet connection.31+32+This will install Jinja into your Python installation's site-packages directory.33+34+35+Installing the development version36+==================================37+38+If you want to play around with the code39+----------------------------------------40+41+1. Install `Subversion`_42+2. ``svn co http://trac.pocoo.org/repos/jinja/trunk jinja``43+3. ``cd jinja``44+4. ``ln -s jinja /usr/lib/python2.X/site-packages``45+46+As an alternative to steps 4 you can also do ``python setup.py develop``47+which will install the package via setuptools in development mode.48+49+If you just want the latest features and use them50+-------------------------------------------------51+52+::53+ 54+ sudo easy_install Jinja==dev55+56+This will install a Jinja egg containing the latest Subversion trunk code57+in your Python installation's site-packages directory. Every time the command58+is run, the sources are updated from Subversion.59+60+61+.. _download page: http://jinja.pocoo.org/download/62+.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools63+.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall64+.. _Subversion: http://subversion.tigris.org/modified:docs/src/loaders.txt+58 added
6 unmodified lines7 Builtin Loaders8 ===============9 10 [[list_of_loaders]]11+12+Developing Loaders13+==================14+15+Template loaders are just normal python classes that have to provide some16+functions used to load and translate templates. Here a simple loader implementation17+you can use as base for your own loader:18+19+.. sourcecode:: python20+21+ from os.path import join22+ from jinja.parser import Parser23+ from jinja.exceptions import TemplateNotFound24+25+ class SimpleLoader(object):26+ """27+ Slimmed down version of the included `FileSystemLoader`.28+ """29+30+ def __init__(self, searchpath):31+ self.searchpath = searchpath32+33+ def get_source(self, environment, name, parent):34+ """35+ The get_source function is unused at the moment. However future36+ versions of jinja will use this function for the debugging37+ system. It also works as helper functions for `parse` and38+ `load`.39+ """40+ filename = join(self.searchpath, name)41+ if not path.exists(filename):42+ raise TemplateNotFound(name)43+ f = codecs.open(filename, 'r', environment.template_charset)44+ try:45+ return f.read()46+ finally:47+ f.close()48+49+ def parse(self, environment, name, parent):50+ """51+ Load and parse a template and return the syntax tree.52+ """53+ source = self.get_source(environment, name, parent)54+ return Parser(environment, source, name).parse()55+56+ def load(self, environment, name, translator):57+ """58+ Parse and translate a template. Currently only translation to59+ python code is possible, later jinja versions however will60+ support translating templates to javascript too.61+ """62+ return translator.process(environment, self.parse(environment, name, None))63+64+65+.. admonition:: Note66+67+ Once a loader is bound to an environment you have to omit the environment68+ argument for the public functions `get_source`, `parse` and `load`.added:docs/src/tests.txt+30 added
1+==============2+Test Functions3+==============4+5+Additionally to filters Jinja also supports test functions. Test functions6+always return either ``True`` or ``False``. Inside the template they are available7+using the `is` operator.8+9+Jinja comes with some builtin tests listed in the `designer documentation`_.10+11+Writing Test Functions12+======================13+14+Test functions look exactly like filters mentioned in the `filter documentation`_:15+16+.. sourcecode:: python17+18+ def is_even():19+ def wrapped(env, context, value):20+ return value % 2 == 021+ return wrapped22+23+Now you have to register that test on an environment:24+25+.. sourcecode:: python26+27+ env.tests['even'] = is_even28+29+.. _designer documentation: designerdoc.txt30+.. _filter documentation: filters.txtadded:docs/src/translators.txt+10 added
1+===========2+Translators3+===========4+5+Jinja translates the template sourcecode into executable python code behind6+the secenes. This is done by the python translator which is currently the7+only shipped translator. Because the interface isn't stable it's also not8+recommended to write other translators. However for the next Jinja version9+a JavaScript translator is planned which allows you to translate Jinja10+templates into executable JavaScript code.modified:jinja/translators/__init__.py+1 added-1 removed
4 unmodified lines5 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.9+ :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12 13 17 unmodified linesmodified:jinja/translators/python.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~~~~~~~~5 6 This module translates a jinja ast into python code.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from compiler import ast12 from jinja import nodes708 unmodified linesmodified:jinja/__init__.py+1 added-1 removed
1 unmodified line2 """3 Jinja Sandboxed Template Engine4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5 6- :copyright: 2006 by Armin Ronacher.6+ :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 from jinja.environment import Environment10 from jinja.loaders import *added:jinja/bakerplugin.py+93 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.bakerplugin4+ ~~~~~~~~~~~~~~~~~5+6+ Provide a bridge to baker. Baker is used by some frameworks (namely7+ CherryPy, TurboGears and Pylons) to load templates.8+9+ :copyright: 2007 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""12+from jinja import Environment13+14+15+class ConfigurationError(Exception):16+ """17+ Raised if an configuration error occoured.18+ """19+20+21+class JinjaPlugin(object):22+ """23+ Implementation of the Plugin API24+ """25+ extension = 'html'26+27+ def __init__(self, extra_vars_func=None, options=None):28+ self.get_extra_vars = extra_vars_func29+ options = options or {}30+ self.extension = options.get('jinja.extension', JinjaPlugin.extension)31+ if 'jinja.environment' in options:32+ self.environment = options['jinja.environment']33+ else:34+ # this wonderful piece of code was brought to you by the turbogears35+ # ppl who want to put template configuration stuff into goddamn36+ # text/plain configuration files.37+ if 'jinja.environment.loader' in options:38+ loader = options['jinja.environment.loader']39+ else:40+ loadername = options.get('jinja.loader') or 'FileSystemLoader'41+ if '.' in loadername:42+ p = loadername.rsplit('.', 1)43+ loadercls = getattr(__import__(p[0], '', '', ['']), p[1])44+ else:45+ from jinja import loaders46+ loadercls = getattr(loaders, loadername)47+ loaderoptions = {}48+ for k, v in options.iteritems():49+ if k.startswith('jinja.loader.'):50+ loaderoptions[k[14:]] = v51+ loader = loadercls(**loaderoptions)52+ self.environment = Environment(53+ block_start_string=options.get('jinja.block_start_string', '{%'),54+ block_end_string=options.get('jinja.block_end_string', '%}'),55+ variable_start_string=options.get('jinja.variable_start_string', '{{'),56+ variable_end_string=options.get('jinja.variable_end_string', '}}'),57+ comment_start_string=options.get('jinja.comment_start_string', '{#'),58+ comment_end_string=options.get('jinja.comment_end_string', '#}'),59+ trim_blocks=str(options.get('jinja.trim_blocks')).lower() in60+ ('true', 'on', 'yes', '1'),61+ template_charset=options.get('jinja.template_charset', 'utf-8'),62+ charset=options.get('jinja.charset', 'utf-8'),63+ namespace=options.get('jinja.namespace'),64+ loader=loader,65+ filters=options.get('jinja.filters'),66+ tests=options.get('jinja.tests')67+ )68+69+ def load_template(self, templatename, template_string=None):70+ """71+ Find a template specified in python 'dot' notation, or load one from72+ a string.73+ """74+ if template_string is not None:75+ return self.environment.from_string(template_string)76+77+ # Translate TG dot notation to normal / template path78+ if '/' not in templatename and '.' not in templatename:79+ templatename = '/' + templatename.replace('.', '/') + '.' + self.extension80+81+ return self.environment.get_template(templatename)82+83+ def render(self, info, format='html', fragment=False, template=None):84+ """85+ Render a template.86+ """87+ if isinstance(template, basestring):88+ template = self.load_template(template)89+90+ if self.get_extra_vars:91+ info.update(self.get_extra_vars())92+93+ return template.render(**info)modified:jinja/datastructure.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~~~5 6 Module that helds several data types used in the template engine.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 # python2.3 compatibility. do not use this method for anything else286 unmodified linesmodified:jinja/defaults.py+2 added-2 removed
3 unmodified lines4 ~~~~~~~~~~~~~~5 6 Jinja default filters and tags.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :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+#: for global objects in later jinja releases. (add stuff like debug())16 DEFAULT_NAMESPACE = {16- 'range': xrange17 }modified:jinja/environment.py+2 added-2 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~~5 6 Provides a class that holds runtime and parsing time options.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12 from jinja.lexer import Lexer54 unmodified lines67 """68 Get or set the template loader.69 """70 self._loader = LoaderWrapper(self, value)71- loader = property(lambda s: s._loader.loader, loader, loader.__doc__)71+ loader = property(lambda s: s._loader, loader, loader.__doc__)72 73 def parse(self, source, filename=None):74 """Function that creates a new parser and parses the source."""75 parser = Parser(self, source, filename)103 unmodified linesmodified:jinja/exceptions.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~~~~~5 6 Jinja exceptions.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 56 unmodified linesmodified:jinja/filters.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~~5 6 Bundled jinja filters.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from random import choice12 from urllib import urlencode, quote307 unmodified linesmodified:jinja/lexer.py+1 added-1 removed
1 unmodified line2 """3 jinja.lexer4 ~~~~~~~~~~~5 6- :copyright: 2006 by Armin Ronacher.6+ :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 import re10 from jinja.datastructure import TokenStream199 unmodified linesmodified:jinja/loaders.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~~5 6 Jinja loader classes.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12 import codecs117 unmodified linesmodified:jinja/nodes.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~5 6 Additional nodes for jinja. Look like nodes from the ast.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from compiler import ast12 from compiler.misc import set_filename290 unmodified linesmodified:jinja/parser.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~~5 6 Implements the template parser.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12 from compiler import ast, parse339 unmodified linesmodified:jinja/tests.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~5 6 Jinja test functions. Used with the "is" operator.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12 from jinja.datastructure import Undefined114 unmodified linesmodified:jinja/utils.py+1 added-1 removed
3 unmodified lines4 ~~~~~~~~~~~5 6 Utility functions.7 8- :copyright: 2006 by Armin Ronacher.8+ :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 import re12 from jinja.datastructure import safe_types, Markup22 unmodified linesmodified:setup.py+14 added-77 removed
7 unmodified lines8 9 10 setup(11 name = 'Jinja',12- version = '0.9',13- url = 'http://wsgiarea.pocoo.org/jinja/',12+ version = '1.0',13+ url = 'http://jinja.pocoo.org/',14 license = 'BSD',15 author = 'Armin Ronacher',16 author_email = 'armin.ronacher@active-4.com',17 description = 'A small but fast and easy to use stand-alone template engine written in pure python.',18- long_description = '''\19-Jinja is a small but very fast and easy to use stand-alone template engine20-written in pure Python.21-22-Since version 0.6 it uses a new parser that increases parsing performance23-a lot by caching the nodelists on disk if wanted.24-25-It includes multiple template inheritance and other features like simple26-value escaping.27-28-29-Template Syntax30-===============31-32-This is a small example template in which you can see how Jinja's syntax33-looks like::34-35- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"36- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">37- <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">38- <head>39- <title>My Webpage</title>40- </head41- <body>42- <ul id="navigation">43- {% for item in navigation %}44- <li><a href="{{ item.href }}">{{ item.caption|e }}</a></li>45- {% endfor %}46- </ul>47-48- <h1>My Webpage</h1>49- {{ variable }}50- </body>51- </html>52-53-54-Usage55-=====56-57-Here is a small example::58-59- from jinja import Template, Context, FileSystemLoader60-61- t = Template('mytemplate', FileSystemLoader('/path/to/the/templates'))62- c = Context({63- 'navigation' [64- {'href': '#', 'caption': 'Index'},65- {'href': '#', 'caption': 'Spam'}66- ],67- 'variable': '<strong>hello world</strong>'68- })69- print t.render(c)70-71-72-Unicode Support73-===============74-75-Jinja comes with built-in Unicode support. As a matter of fact, the return76-value of ``Template.render()`` will be a Python unicode object.77-78-You can still output ``str`` objects as well when you encode the result::79-80- s = t.render(c).encode('utf-8')81-82-For more examples check out the `documentation`_ on the `jinja webpage`_.83-84-.. _documentation: http://wsgiarea.pocoo.org/jinja/docs/85-.. _jinja webpage: http://wsgiarea.pocoo.org/jinja/86-''',87- keywords = 'wsgi web templateengine templates',88- packages = ['jinja'],89- platforms = 'any',18+ zip_safe = True,19 classifiers = [20 'Development Status :: 5 - Production/Stable',21 'Environment :: Web Environment',22 'Intended Audience :: Developers',23 'License :: OSI Approved :: BSD License',24 'Operating System :: OS Independent',25 'Programming Language :: Python',97- 'Topic :: Internet :: WWW/HTTP',98- 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'99- ]26+ 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',27+ 'Topic :: Software Development :: Libraries :: Python Modules',28+ 'Topic :: Text Processing :: Markup :: HTML'29+ ],30+ keywords = ['python.templating.engines'],31+ packages = ['jinja'],32+ extras_require = {'plugin': ['setuptools>=0.6a2']},33+ entry_points='''34+ [python.templating.engines]35+ jinja = jinja.bakerplugin:JinjaPlugin[plugin]36+ '''37 )