Skip to content
Myr

some more doc changes in jinja for the upcoming release

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 c9fe16e · Browse files · 12 files+196 added−20 removed
This commit

State

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

Diff stats

12 files+196 added−20 removed

  • tests:+16 added−0 removed
  • other:+180 added−20 removed

12 files+196 added−20 removed

modified:docs/src/debugging.txt+12 added-7 removed
6 unmodified lines
7does not support the `__loader__` hook which is used by Jinja to provide8templates. Although the import system was implemented three Python versions9ago the default traceback system still doesn't support it.1011However most of the extended web development traceback module support it:11However most of the extended web development traceback modules have support12for `__loader__`. Either directly or via the linecache module:1313- `Colubrid Debugging Middleware`_14- `Werkzeug Debugging Middleware`_15- `Django`_16- `cgitb`_17- `EvalException`_1817Note that the django traceback module currently does not provide this. `A18ticket`_ was filed already so there is hope that this will be fixed.1919To enable debugging you have to use one of those debugging systems or20implement your own one with support for `__loader__`.2122The python implementation of the jinja debugger can only translate the first23exception in a traceback which can lead to problematic results. If you have24the extended debugger c extension compiled (default on unix systems but only25available on Windows if you have a VisualStudio 2003 installation) all frames26in the traceback will point to the correct linenumbers of the templates.2724.. _Colubrid Debugging Middleware: http://trac.pocoo.org/repos/colubrid/trunk/colubrid/debug.py2829.. _Werkzeug Debugging Middleware: http://werkzeug.pocoo.org/30.. _Django: http://www.djangoproject.com/31.. _cgitb: http://docs.python.org/lib/module-cgitb.html32.. _EvalException: http://pythonpaste.org/module-paste.evalexception.html27.. _A ticket: http://code.djangoproject.com/ticket/3734
modified:docs/src/designerdoc.txt+8 added
221 unmodified lines
222 ``none`` corresponds to `None` in python.223 ``undefined`` special Jinja undefined singleton.224 ======================= ===================================================225226.. admonition:: Common Pitfalls227228 Keep in mind that Jinja literals, keywords and functions are all lowercase.229 If you're used to Python you probably tried to write `True` which evaluates230 to undefined because it simply does not exist. The correct name for the231 true value is just `true` (lowercase).232 233234Operators235=========236237Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can
328 unmodified lines
modified:docs/src/devrecipies.txt+12 added
36 unmodified lines
37 return env.autorender('foo.html')3839In the template you can now access the local variables `seq` and `foo`.404142Using Django Filters with Jinja43===============================4445If you use Jinja in django and want to use some of the filters that
29 unmodified lines
7576Also keep in mind that Jinja knows about keywords, thus you cannot have a filter77that is called `pluralize` for example.7879Such a conversion function is also part of the djangosupport module which was80introduced in Jinja 1.2. It's explained on the `Framework Integration`_ page.818283Using Jinja in Django84=====================8586.. admonition:: Note8788 This section is more or less obsolete as of Jinja 1.2 which provides a89 djangosupport module, covered on the `Framework Integration`_ page.9091This snippet was contributed by Bryan McLemore. It provides a `render_to_response`92function similar to the one shipped with django just that it uses Jinja for93rendering. It applies the context processors on the context and consumes a94`RequestContext`:
38 unmodified lines
133 return DjangoTranslator()134135Because Django uses gettext internally we can create just assign the136ngettext and gettext functions directly to the translator class.137138139.. _Framework Integration: frameworks.txt
modified:docs/src/escaping.txt+2 added-2 removed
38 unmodified lines
39processing).4041Starting with `Jinja 1.1` you can also handle some whitespace rules in the42template. If you put an minus sign (`-`) to the start or end of an block43(for example a `for` tag) or a comment, variable element you can remove44the whitespaces after that block or before that block:43(for example a `for` tag), a comment or variable element you can remove44the whitespaces after or before that block:4546.. sourcecode:: jinja4748 {% for item in seq -%}
23 unmodified lines
modified:docs/src/frameworks.txt+108 added-1 removed
13 unmodified lines
14called `General Template Interface`_ which isn't implemented by any existing15framework so far. This specification however tries to solve the problems that16exist in Buffet.171819Buffet20======2122The buffet specification proposes that templates are named in dotted names. That
85 unmodified lines
108a folder in the ``yourapplication`` python package.109110The `downloads` action uses the pylons specific leading foreslash notation.111112113General Template Interface114==========================115116Because nobody implemented this specification so far it's not documented here
5 unmodified lines
122======123124Using Jinja in django is straightforward because django has a pretty low125level response interface. Just have a look at the `developer recipies`_,124there are some examples for django.126there are some examples for django. Starting with Jinja 1.2 there is also127a contrib module that simplifies using Jinja in an unicode enabled django.128129Quickstart130----------131132To get started execute the following code at the bottom of your settings.py133or in some general application file such as urls.py or a central module. The134only thing that matters is that it's executed right *after* the settings135were set up and *before* `django.contrib.jinja` is imported::136137 from jinja.contrib import djangosupport138 djangosupport.configure()139140What this does is setting up a Jinja environment for this django instance141with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default142django filters such as `date` and `timesince` which are not available in143Jinja per default. If you want to change the list you can provide others144by passing a list with filter import names as `convert_filters` keyword145argument.146147All other keyword arguments are forwarded to the environment. If you want148to provide a loader yourself pass it a loader keyword argument.149150Rendering Templates151-------------------152153To render a template you can use the functions `render_to_string` or154`render_to_response` from the `django.contrib.jinja` module::155156 from django.contrib.jinja import render_to_response157 resp = render_to_response('Hello {{ username }}!', {158 'username': req.session['username']159 }, req)160161`render_to_string` and `render_to_response` take at least the name of162the template as argument, then the optional dict which will become the163context. If you also provide a request object as third argument the164context processors will be applied.165166`render_to_response` also takes a forth parameter which can be the167content type which defaults to `DEFAULT_CONTENT_TYPE`.168169Converting Filters170------------------171172One of the useful objects provided by `django.contrib.jinja` is the173`register` object which can be used to register filters, tests and174global objects. You can also convert any filter django provides in175a Jinja filter using `convert_django_filter`::176177 from django.contrib.jinja import register, convert_django_filter178 from django.template.defaultfilters import floatformat179180 register.filter(convert_django_filter(floatformat), 'floatformat')181182Available methods on the `register` object:183184``object (obj[, name])``185 Register a new global as name or with the object's name.186 Returns the function object unchanged so that you can use187 it as decorator if no name is provided.188189``filter (func[, name])``190 Register a function as filter with the name provided or191 the object's name as filtername.192 Returns the function object unchanged so that you can use193 it as decorator if no name is provided.194195``test (func[, name])``196 Register a function as test with the name provided or the197 object's name as testname.198 Returns the function object unchanged so that you can use199 it as decorator if no name is provided.200201``context_inclusion (func, template[, name])``202 Register a function with a name provided or the func object's203 name in the global namespace that acts as subrender function.204205 func is called with the callers context as dict and the206 arguments and keywords argument of the inclusion function.207 The function should then process the context and return a208 new context or the same context object. Afterwards the209 template is rendered with this context.210211 Example::212213 def add_author(context, author=None):214 if author is not None:215 author = Author.objects.get(name=author)216 context['author'] = author217 return context218219 register.context_inclusion(add_author, 'author_details.html',220 'render_author_details')221222 You can use it in the template like this then::223224 {{ render_author_details('John Doe') }}225226``clean_inclusion (func, template[, name[, run_processors]]) ``227 Works like `context_inclusion` but doesn't use the calles228 context but an empty context. If `run_processors` is `True`229 it will lookup the context for a `request` object and pass230 it to the render function to apply context processors.231232233234.. _Pylons: http://www.pylonshq.com/235.. _General Template Interface: http://trac.pocoo.org/wiki/GeneralTemplateInterface236.. _plugin module: http://trac.pocoo.org/browser/jinja/trunk/jinja/plugin.py237.. _developer recipies: devrecipies.txt
modified:docs/src/installation.txt+17 added-1 removed
2 unmodified lines
3============45Jinja requires at least Python 2.3 to work correctly.678Installing a released version9=============================1011As a Python egg (via easy_install)
18 unmodified lines
30internet 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 code
4 unmodified lines
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``45which will install the package via setuptools in development mode.47which will install the package via setuptools in development mode. This also48has the advantage that the c extensions are compiled.4950If you just want the latest features and use them51-------------------------------------------------52
4 unmodified lines
57This will install a Jinja egg containing the latest Subversion trunk code58in your Python installation's site-packages directory. Every time the command59is run, the sources are updated from Subversion.606162Windows Installation Information63================================6465On windows computers without Visual Studio 2003 Jinja is unable to compile the66C extensions. This is usually not a problem because there is a fallback for67native Python implementations of those C libraries. However under certain68conditions the installation may fail with an error message. In that case try69to disable the extensions by passing the following parameters to setup.py::7071 python setup.py install --without-speedups --without-extended-debugger727374Documentation75=============7677The egg builds include a documentation which is available in the ``docs`` folder
12 unmodified lines
modified:docs/src/scopes.txt+2 added-3 removed
180 unmodified lines
181 {% endfor %}182183After the iteration `last_item` will point to the item of the last iteration.184185If `last_item` was not defined in the outer scope it wouldn't exist now because186in that situation `set`, even with a postfixed bang just behaves like setting a187scope variable.185If `last_item` was not defined in the outer scope it would be defined in the186outermost scope.
modified:jinja/datastructure.py+1 added-1 removed
272 unmodified lines
273 for layer in self.stack[:0:-1]:274 if name in layer:275 layer[name] = value276 return277 self.current[name] = value277 self.initial[name] = value278279 def translate_func(self):280 """281 The translation function for this context. It takes
427 unmodified lines
modified:tests/test_security.py+16 added
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment101112NONLOCALSET = '''\13{% for item in range(10) %}14 {%- set outer = item! -%}15{% endfor -%}16{{ outer }}'''171819class PrivateStuff(object):20 bar = lambda self: 2321 foo = lambda self: 4222 foo.jinja_unsafe_call = True
33 unmodified lines
56Traceback (most recent call last):57 ...58TemplateSyntaxError: cannot assign to expression (line 1)59'''606162def test_nonlocal_set():63 env = Environment()64 env.globals['outer'] = 4265 tmpl = env.from_string(NONLOCALSET)66 assert tmpl.render() == '9'67 assert env.globals['outer'] == 42
added:.hgignore+6 added
1^instance$2^instance/3^jinja/.*\.so$4^(build|dist|Jinja\.egg-info)/5\.py[co]$6\.DS_Store$
modified:CHANGES+8 added-1 removed
1 unmodified line
2===============34Version 1.25-----------6(codename to be selected, release date unknown)6(codename to be hatsuyuki, released Nov 17th 2007)78.. admonition:: Backwards Incompatible Changes910 - `call` is a keyword now11 - the internal parser AST changed12 - `extends` must be the first tag in a template13 - the tuple literal yields tuples now, instead of lists.1415- environments now have a `translator_factory` parameter that allows16 to change the translator without subclassing the environment.1718- fixed bug in buffet plugin regarding the package loader
199 unmodified lines
modified:setup.py+4 added-4 removed
88 unmodified lines
89 extras_require={'plugin': ['setuptools>=0.6a2']},90 features={91 'speedups': Feature(92 'optional C-speed enhancements',93 standard = True,94 ext_modules = [93 standard=True,94 ext_modules=[95 Extension('jinja._speedups', ['jinja/_speedups.c'])96 ]97 ),98 'extended-debugger': Feature(99 'extended debugger',100 standard = True,101 ext_modules = [100 standard=True,101 ext_modules=[102 Extension('jinja._debugger', ['jinja/_debugger.c'])103 ]104 )105 },
2 unmodified lines