Skip to content
Myr

[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

21 files+342 added−93 removed

added:docs/src/filters.txt+57 added
1================2Filter Functions3================45Filters are a powerful feature of Jinja taken from django which probably took6it from UNIX. The idea is that you "pipe" a value through some filters to7do something with it. For example convert it to upper case, escape it or8replace a substring.910Jinja comes with some builtin filters explained in the `designer documentation`_.1112Writing Filters13===============1415A filter basically is a factory function. Thus a function that returns another16function. We do this because filters can get an unlimited amount of position17arguments and aditionally should gain access to the environment, context and18piped value. A simple filter looks like this:1920.. sourcecode:: python2122 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 wrapped2930Now you have to register that filter on an environment:3132.. sourcecode:: python3334 env.filters['join'] = do_join3536In fact this filter is already bundled so you won't see any effect. But its37should explain how such a filter looks like. The template designer can just38trigger the outer code (eg: call do_join with or without arguments). The39returned function is then processed by the jinja template engine once all40filters are created.4142If you want to create filters that just operate on string (in fact unicode43objects) you can use the `stringfilter` decorator:4445.. sourcecode:: python4647 from jinja.filters import stringfilter4849 @stringfilter50 def do_strip(value):51 return value.strip()5253The wrapped function is created internally by the decorator, any positional54arguments are forwarded to the filter function. The first argument is always55the value already converted into a string.5657.. _designer documentation: designerdoc.txt
added:docs/src/installation.txt+64 added
1============2Installation3============45Jinja requires at least Python 2.3 to work correctly.67Installing a released version8=============================910As a Python egg (via easy_install)11----------------------------------1213You can install the most recent Jinja version using `easy_install`_::1415 sudo easy_install Jinja1617This will install a Jinja egg in your Python installation's site-packages18directory.192021From the tarball release22-------------------------23241. Download the most recent tarball from the `download page`_252. Unpack the tarball263. ``sudo python setup.py install``2728Note that the last command will automatically download and install29`setuptools`_ if you don't already have it installed. This requires a working30internet connection.3132This will install Jinja into your Python installation's site-packages directory.333435Installing the development version36==================================3738If you want to play around with the code39----------------------------------------40411. Install `Subversion`_422. ``svn co http://trac.pocoo.org/repos/jinja/trunk jinja``433. ``cd jinja``444. ``ln -s jinja /usr/lib/python2.X/site-packages``4546As an alternative to steps 4 you can also do ``python setup.py develop``47which will install the package via setuptools in development mode.4849If you just want the latest features and use them50-------------------------------------------------5152::53 54 sudo easy_install Jinja==dev5556This will install a Jinja egg containing the latest Subversion trunk code57in your Python installation's site-packages directory. Every time the command58is run, the sources are updated from Subversion.596061.. _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 lines
7Builtin Loaders8===============910[[list_of_loaders]]1112Developing Loaders13==================1415Template loaders are just normal python classes that have to provide some16functions used to load and translate templates. Here a simple loader implementation17you can use as base for your own loader:1819.. sourcecode:: python2021 from os.path import join22 from jinja.parser import Parser23 from jinja.exceptions import TemplateNotFound2425 class SimpleLoader(object):26 """27 Slimmed down version of the included `FileSystemLoader`.28 """2930 def __init__(self, searchpath):31 self.searchpath = searchpath3233 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()4849 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()5556 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))636465.. admonition:: Note6667 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==============2Test Functions3==============45Additionally to filters Jinja also supports test functions. Test functions6always return either ``True`` or ``False``. Inside the template they are available7using the `is` operator.89Jinja comes with some builtin tests listed in the `designer documentation`_.1011Writing Test Functions12======================1314Test functions look exactly like filters mentioned in the `filter documentation`_:1516.. sourcecode:: python1718 def is_even():19 def wrapped(env, context, value):20 return value % 2 == 021 return wrapped2223Now you have to register that test on an environment:2425.. sourcecode:: python2627 env.tests['even'] = is_even2829.. _designer documentation: designerdoc.txt30.. _filter documentation: filters.txt
added:docs/src/translators.txt+10 added
1===========2Translators3===========45Jinja translates the template sourcecode into executable python code behind6the secenes. This is done by the python translator which is currently the7only shipped translator. Because the interface isn't stable it's also not8recommended to write other translators. However for the next Jinja version9a JavaScript translator is planned which allows you to translate Jinja10templates into executable JavaScript code.
modified:jinja/translators/__init__.py+1 added-1 removed
4 unmodified lines
56 The submodules of this module provide translators for the jinja ast7 which basically just is the python ast with a few more nodes.89 :copyright: 2006 by Armin Ronacher.9 :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213
17 unmodified lines
modified:jinja/translators/python.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~~~~~~~~56 This module translates a jinja ast into python code.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from compiler import ast12from jinja import nodes
708 unmodified lines
modified:jinja/__init__.py+1 added-1 removed
1 unmodified line
2"""3 Jinja Sandboxed Template Engine4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2006 by Armin Ronacher.6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja.environment import Environment10from jinja.loaders import *
added:jinja/bakerplugin.py+93 added
1# -*- coding: utf-8 -*-2"""3 jinja.bakerplugin4 ~~~~~~~~~~~~~~~~~56 Provide a bridge to baker. Baker is used by some frameworks (namely7 CherryPy, TurboGears and Pylons) to load templates.89 :copyright: 2007 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""12from jinja import Environment131415class ConfigurationError(Exception):16 """17 Raised if an configuration error occoured.18 """192021class JinjaPlugin(object):22 """23 Implementation of the Plugin API24 """25 extension = 'html'2627 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 )6869 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)7677 # Translate TG dot notation to normal / template path78 if '/' not in templatename and '.' not in templatename:79 templatename = '/' + templatename.replace('.', '/') + '.' + self.extension8081 return self.environment.get_template(templatename)8283 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)8990 if self.get_extra_vars:91 info.update(self.get_extra_vars())9293 return template.render(**info)
modified:jinja/datastructure.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~~~56 Module that helds several data types used in the template engine.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112# python2.3 compatibility. do not use this method for anything else
286 unmodified lines
modified:jinja/defaults.py+2 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~56 Jinja default filters and tags.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS131415#: for global objects in later jinja releases. (add stuff like debug())16DEFAULT_NAMESPACE = {16 'range': xrange17}
modified:jinja/environment.py+2 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~56 Provides a class that holds runtime and parsing time options.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.lexer import Lexer
54 unmodified lines
67 """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__)7273 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 lines
modified:jinja/exceptions.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~56 Jinja exceptions.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112
56 unmodified lines
modified:jinja/filters.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~~56 Bundled jinja filters.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from random import choice12from urllib import urlencode, quote
307 unmodified lines
modified:jinja/lexer.py+1 added-1 removed
1 unmodified line
2"""3 jinja.lexer4 ~~~~~~~~~~~56 :copyright: 2006 by Armin Ronacher.6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9import re10from jinja.datastructure import TokenStream
199 unmodified lines
modified:jinja/loaders.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~~56 Jinja loader classes.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import codecs
117 unmodified lines
modified:jinja/nodes.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~56 Additional nodes for jinja. Look like nodes from the ast.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from compiler import ast12from compiler.misc import set_filename
290 unmodified lines
modified:jinja/parser.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~~56 Implements the template parser.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from compiler import ast, parse
339 unmodified lines
modified:jinja/tests.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~56 Jinja test functions. Used with the "is" operator.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.datastructure import Undefined
114 unmodified lines
modified:jinja/utils.py+1 added-1 removed
3 unmodified lines
4 ~~~~~~~~~~~56 Utility functions.78 :copyright: 2006 by Armin Ronacher.8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from jinja.datastructure import safe_types, Markup
22 unmodified lines
modified:setup.py+14 added-77 removed
7 unmodified lines
8910setup(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 = '''\19Jinja is a small but very fast and easy to use stand-alone template engine20written in pure Python.2122Since version 0.6 it uses a new parser that increases parsing performance23a lot by caching the nodelists on disk if wanted.2425It includes multiple template inheritance and other features like simple26value escaping.272829Template Syntax30===============3132This is a small example template in which you can see how Jinja's syntax33looks like::3435 <!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>4748 <h1>My Webpage</h1>49 {{ variable }}50 </body>51 </html>525354Usage55=====5657Here is a small example::5859 from jinja import Template, Context, FileSystemLoader6061 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)707172Unicode Support73===============7475Jinja comes with built-in Unicode support. As a matter of fact, the return76value of ``Template.render()`` will be a Python unicode object.7778You can still output ``str`` objects as well when you encode the result::7980 s = t.render(c).encode('utf-8')8182For more examples check out the `documentation`_ on the `jinja webpage`_.8384.. _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)