From: Armin Ronacher Date: Thu, 17 Apr 2008 09:16:01 +0000 (+0200) Subject: updated a few docstrings and removed contrib X-Git-Tag: 2.0rc1~158 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=26c0f51140066998e5054b0e867e950d6dcfc369;p=jinja2.git updated a few docstrings and removed contrib --HG-- branch : trunk --- diff --git a/jinja2/contrib/__init__.py b/jinja2/contrib/__init__.py deleted file mode 100644 index 1770052..0000000 --- a/jinja2/contrib/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# -*- coding: utf-8 -*- -""" - jinja.contrib - ~~~~~~~~~~~~~ - - This module collections various third-party helper functions and classes - that are useful for frameworks etc. - - :copyright: 2007 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" diff --git a/jinja2/contrib/_djangosupport.py b/jinja2/contrib/_djangosupport.py deleted file mode 100644 index 65a192e..0000000 --- a/jinja2/contrib/_djangosupport.py +++ /dev/null @@ -1,209 +0,0 @@ -# -*- coding: utf-8 -*- -""" - jinja.contrib._djangosupport - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Django suport layer. This module is a metamodule, do never import it - directly or access any of the functions defined here. - - The public interface is `jinja.contrib.djangosupport` and - `django.contrib.jinja`. See the docstring of `jinja.contrib.djangosupport` - for more details. - - :copyright: 2007-2008 by Armin Ronacher, Bryan McLemore, David Cramer. - :license: BSD, see LICENSE for more details. -""" -import sys -import warnings -import new -from django.conf import settings -from django.template.context import get_standard_processors -from django.http import HttpResponse -from django import contrib - -from jinja import Environment, FileSystemLoader, ChoiceLoader -from jinja.loaders import MemcachedFileSystemLoader - - -exported = ['render_to_response', 'render_to_string', 'convert_django_filter'] - - -#: used environment -env = None - - -#: default filters -DEFAULT_FILTERS = ( - 'django.template.defaultfilters.date', - 'django.template.defaultfilters.timesince', - 'django.template.defaultfilters.linebreaks', - 'django.contrib.humanize.templatetags.humanize.intcomma' -) - -def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options): - """ - Initialize the system. - """ - global env - - if env: - warnings.warn("Jinja already initialized.") - return - - # setup environment - if loader is None: - loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS) - if not loaders: - loader = None - elif len(loaders) == 1: - loader = loaders[0] - else: - loader = ChoiceLoader(loaders) - env = Environment(loader=loader, **options) - - # convert requested filters - for name in convert_filters: - env.filters[name] = convert_django_filter(name) - - # import templatetags of installed apps - for app in settings.INSTALLED_APPS: - try: - __import__(app + '.templatetags') - except ImportError: - pass - - # setup the django.contrib.jinja module - setup_django_module() - - -def setup_django_module(): - """ - create a new Jinja module for django. - """ - from jinja.contrib import djangosupport - module = contrib.jinja = sys.modules['django.contrib.jinja'] = \ - new.module('django.contrib.jinja') - module.env = env - module.__doc__ = djangosupport.__doc__ - module.register = Library - public_names = module.__all__ = ['register', 'env'] - get_name = globals().get - for name in exported: - setattr(module, name, get_name(name)) - public_names.append(name) - - -def render_to_response(template, context={}, request=None, - mimetype=None): - """This function will take a few variables and spit out a full webpage.""" - content = render_to_string(template, context, request) - if mimetype is None: - mimetype = settings.DEFAULT_CONTENT_TYPE - return HttpResponse(content, mimetype) - - -def render_to_string(template, context={}, request=None): - """Render a template to a string.""" - assert env is not None, 'Jinja not configured for django' - if request is not None: - context['request'] = request - for processor in get_standard_processors(): - context.update(processor(request)) - template = env.get_template(template) - return template.render(context) - - -def convert_django_filter(f): - """Convert a django filter into a Jinja filter.""" - if isinstance(f, str): - p = f.split('.') - f = getattr(__import__('.'.join(p[:-1]), None, None, ['']), p[-1]) - def filter_factory(*args): - def wrapped(env, ctx, value): - return f(value, *args) - return wrapped - filter_factory.__name__ = f.__name__ - filter_factory.__doc__ = getattr(f, '__doc__', None) - return filter_factory - - -class Library(object): - """ - Continues a general feel of wrapping all the registration - methods for easy importing. - - This is available in `django.contrib.jinja` as `register`. - - For more details see the docstring of the `django.contrib.jinja` module. - """ - def object(func, name=None): - """Register a new global.""" - if name is None: - name = getattr(func, '__name__') - env.globals[name] = func - return func - object = staticmethod(object) - - def filter(func, name=None): - """Register a new filter function.""" - if name is None: - name = func.__name__ - env.filters[name] = func - return func - filter = staticmethod(filter) - - def test(func, name): - """Register a new test function.""" - if name is None: - name = func.__name__ - env.tests[name] = func - return func - test = staticmethod(test) - - def context_inclusion(func, template, name=None): - """ - Similar to the inclusion tag from django this one expects func to be a - function with a similar argument list to func(context, *args, **kwargs) - - It passed in the current context allowing the function to edit it or read - from it. the function must return a dict with which to pass into the - renderer. Normally expected is an altered dictionary. - - Note processors are NOT ran on this context. - """ - def wrapper(env, context, *args, **kwargs): - context = func(context.to_dict(), *args, **kwargs) - return render_to_string(template, context) - wrapper.jinja_context_callable = True - if name is None: - name = func.__name__ - try: - wrapper.__name__ = func.__name__ - wrapper.__doc__ = func.__doc__ - except: - pass - env.globals[name] = wrapper - context_inclusion = staticmethod(context_inclusion) - - def clean_inclusion(func, template, name=None, run_processors=False): - """ - Similar to above however it won't pass the context into func(). - Also the returned context will have the context processors run upon it. - """ - def wrapper(env, context, *args, **kwargs): - if run_processors: - request = context['request'] - else: - request = None - context = func({}, *args, **kwargs) - return render_to_string(template, context, request) - wrapper.jinja_context_callable = True - if name is None: - name = func.__name__ - try: - wrapper.__name__ = func.__name__ - wrapper.__doc__ = func.__doc__ - except: - pass - env.globals[name] = wrapper - clean_inclusion = staticmethod(clean_inclusion) diff --git a/jinja2/contrib/djangosupport.py b/jinja2/contrib/djangosupport.py deleted file mode 100644 index 9898a82..0000000 --- a/jinja2/contrib/djangosupport.py +++ /dev/null @@ -1,124 +0,0 @@ -# -*- coding: utf-8 -*- -""" - jinja.contrib.djangosupport - ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Support for the django framework. This module is quite magical because it - just exports one single function, the `configure` function which is used - to create a new Jinja environment and setup a special module called - `django.contrib.jinja` which exports a couple of functions useful for Jinja. - - Quickstart - ========== - - To get started execute the following code at the bottom of your settings.py - or in some general application file such as urls.py or a central module. The - only thing that matters is that it's executed right *after* the settings - were set up and *before* `django.contrib.jinja` is imported:: - - from jinja.contrib import djangosupport - djangosupport.configure() - - What this does is setting up a Jinja environment for this django instance - with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default - django filters such as `date` and `timesince` which are not available in - Jinja per default. If you want to change the list you can provide others - by passing a list with filter import names as `convert_filters` keyword - argument. - - All other keyword arguments are forwarded to the environment. If you want - to provide a loader yourself pass it a loader keyword argument. - - Rendering Templates - =================== - - To render a template you can use the functions `render_to_string` or - `render_to_response` from the `django.contrib.jinja` module:: - - from django.contrib.jinja import render_to_response - resp = render_to_response('Hello {{ username }}!', { - 'username': req.session['username'] - }, req) - - `render_to_string` and `render_to_response` take at least the name of - the template as argument, then the optional dict which will become the - context. If you also provide a request object as third argument the - context processors will be applied. - - `render_to_response` also takes a forth parameter which can be the - content type which defaults to `DEFAULT_CONTENT_TYPE`. - - Converting Filters - ================== - - One of the useful objects provided by `django.contrib.jinja` is the - `register` object which can be used to register filters, tests and - global objects. You can also convert any filter django provides in - a Jinja filter using `convert_django_filter`:: - - from django.contrib.jinja import register, convert_django_filter - from django.template.defaultfilters import floatformat - - register.filter(convert_django_filter(floatformat), 'floatformat') - - Available methods on the `register` object: - - ``object (obj[, name])`` - Register a new global as name or with the object's name. - Returns the function object unchanged so that you can use - it as decorator if no name is provided. - - ``filter (func[, name])`` - Register a function as filter with the name provided or - the object's name as filtername. - Returns the function object unchanged so that you can use - it as decorator if no name is provided. - - ``test (func[, name])`` - Register a function as test with the name provided or the - object's name as testname. - Returns the function object unchanged so that you can use - it as decorator if no name is provided. - - ``context_inclusion (func, template[, name])`` - Register a function with a name provided or the func object's - name in the global namespace that acts as subrender function. - - func is called with the callers context as dict and the - arguments and keywords argument of the inclusion function. - The function should then process the context and return a - new context or the same context object. Afterwards the - template is rendered with this context. - - Example:: - - def add_author(context, author=None): - if author is not None: - author = Author.objects.get(name=author) - context['author'] = author - return context - - register.context_inclusion(add_author, 'author_details.html', - 'render_author_details') - - You can use it in the template like this then:: - - {{ render_author_details('John Doe') }} - - ``clean_inclusion (func, template[, name[, run_processors]]) `` - Works like `context_inclusion` but doesn't use the calles - context but an empty context. If `run_processors` is `True` - it will lookup the context for a `request` object and pass - it to the render function to apply context processors. - - :copyright: 2007 by Armin Ronacher, Bryan McLemore. - :license: BSD, see LICENSE for more details. -""" -try: - __import__('django') -except ImportError: - raise ImportError('installed django required for djangosupport') -else: - from jinja.contrib._djangosupport import configure - -__all__ = ['configure'] diff --git a/jinja2/exceptions.py b/jinja2/exceptions.py index e345f03..f07d860 100644 --- a/jinja2/exceptions.py +++ b/jinja2/exceptions.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """ - jinja.exceptions - ~~~~~~~~~~~~~~~~ + jinja2.exceptions + ~~~~~~~~~~~~~~~~~ Jinja exceptions. diff --git a/jinja2/filters.py b/jinja2/filters.py index c042a5b..137f536 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """ - jinja.filters - ~~~~~~~~~~~~~ + jinja2.filters + ~~~~~~~~~~~~~~ Bundled jinja filters. diff --git a/jinja2/tests.py b/jinja2/tests.py index 405db81..ab7992d 100644 --- a/jinja2/tests.py +++ b/jinja2/tests.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """ - jinja.tests - ~~~~~~~~~~~ + jinja2.tests + ~~~~~~~~~~~~ Jinja test functions. Used with the "is" operator. @@ -37,7 +37,8 @@ def test_defined(value): variable is not defined {% endif %} - See also the ``default`` filter. + See the ``default`` filter for a simple way to set undefined + variables. """ return not isinstance(value, Undefined) @@ -80,8 +81,6 @@ def test_sameas(value, other): {% if foo.attribute is sameas(false) %} the foo attribute really is the `False` singleton {% endif %} - - *New in Jinja 1.2* """ return value is other diff --git a/jinja2/visitor.py b/jinja2/visitor.py index 760fca5..a4dc3d1 100644 --- a/jinja2/visitor.py +++ b/jinja2/visitor.py @@ -12,10 +12,9 @@ from jinja2.nodes import Node class NodeVisitor(object): - """ - Walks the abstract syntax tree and call visitor functions for every node - found. The visitor functions may return values which will be forwarded - by the `visit` method. + """Walks the abstract syntax tree and call visitor functions for every + node found. The visitor functions may return values which will be + forwarded by the `visit` method. Per default the visitor functions for the nodes are ``'visit_'`` + class name of the node. So a `TryFinally` node visit function would @@ -47,8 +46,7 @@ class NodeVisitor(object): class NodeTransformer(NodeVisitor): - """ - Walks the abstract syntax tree and allows modifications of nodes. + """Walks the abstract syntax tree and allows modifications of nodes. The `NodeTransformer` will walk the AST and use the return value of the visitor functions to replace or remove the old node. If the return