updated a few docstrings and removed contrib
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 9a027f4 · Browse files · 7 files·+12 added−359 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+12 added−359 removed
- other:+12 added−359 removed
Provenance
- Commit
26c0f51- Tree
b18e4e3- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9a027f4
7 files changed+12 added−359 removed
deleted:jinja2/contrib/__init__.py-11 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja.contrib4- ~~~~~~~~~~~~~5-6- This module collections various third-party helper functions and classes7- that are useful for frameworks etc.8-9- :copyright: 2007 by Armin Ronacher.10- :license: BSD, see LICENSE for more details.11-"""deleted:jinja2/contrib/_djangosupport.py-209 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja.contrib._djangosupport4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Django suport layer. This module is a metamodule, do never import it7- directly or access any of the functions defined here.8-9- The public interface is `jinja.contrib.djangosupport` and10- `django.contrib.jinja`. See the docstring of `jinja.contrib.djangosupport`11- for more details.12-13- :copyright: 2007-2008 by Armin Ronacher, Bryan McLemore, David Cramer.14- :license: BSD, see LICENSE for more details.15-"""16-import sys17-import warnings18-import new19-from django.conf import settings20-from django.template.context import get_standard_processors21-from django.http import HttpResponse22-from django import contrib23-24-from jinja import Environment, FileSystemLoader, ChoiceLoader25-from jinja.loaders import MemcachedFileSystemLoader26-27-28-exported = ['render_to_response', 'render_to_string', 'convert_django_filter']29-30-31-#: used environment32-env = None33-34-35-#: default filters36-DEFAULT_FILTERS = (37- 'django.template.defaultfilters.date',38- 'django.template.defaultfilters.timesince',39- 'django.template.defaultfilters.linebreaks',40- 'django.contrib.humanize.templatetags.humanize.intcomma'41-)42-43-def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options):44- """45- Initialize the system.46- """47- global env48-49- if env:50- warnings.warn("Jinja already initialized.")51- return52-53- # setup environment54- if loader is None:55- loaders = tuple(FileSystemLoader(l) for l in settings.TEMPLATE_DIRS)56- if not loaders:57- loader = None58- elif len(loaders) == 1:59- loader = loaders[0]60- else:61- loader = ChoiceLoader(loaders)62- env = Environment(loader=loader, **options)63-64- # convert requested filters65- for name in convert_filters:66- env.filters[name] = convert_django_filter(name)67-68- # import templatetags of installed apps69- for app in settings.INSTALLED_APPS:70- try:71- __import__(app + '.templatetags')72- except ImportError:73- pass74-75- # setup the django.contrib.jinja module76- setup_django_module()77-78-79-def setup_django_module():80- """81- create a new Jinja module for django.82- """83- from jinja.contrib import djangosupport84- module = contrib.jinja = sys.modules['django.contrib.jinja'] = \85- new.module('django.contrib.jinja')86- module.env = env87- module.__doc__ = djangosupport.__doc__88- module.register = Library89- public_names = module.__all__ = ['register', 'env']90- get_name = globals().get91- for name in exported:92- setattr(module, name, get_name(name))93- public_names.append(name)94-95-96-def render_to_response(template, context={}, request=None,97- mimetype=None):98- """This function will take a few variables and spit out a full webpage."""99- content = render_to_string(template, context, request)100- if mimetype is None:101- mimetype = settings.DEFAULT_CONTENT_TYPE102- return HttpResponse(content, mimetype)103-104-105-def render_to_string(template, context={}, request=None):106- """Render a template to a string."""107- assert env is not None, 'Jinja not configured for django'108- if request is not None:109- context['request'] = request110- for processor in get_standard_processors():111- context.update(processor(request))112- template = env.get_template(template)113- return template.render(context)114-115-116-def convert_django_filter(f):117- """Convert a django filter into a Jinja filter."""118- if isinstance(f, str):119- p = f.split('.')120- f = getattr(__import__('.'.join(p[:-1]), None, None, ['']), p[-1])121- def filter_factory(*args):122- def wrapped(env, ctx, value):123- return f(value, *args)124- return wrapped125- filter_factory.__name__ = f.__name__126- filter_factory.__doc__ = getattr(f, '__doc__', None)127- return filter_factory128-129-130-class Library(object):131- """132- Continues a general feel of wrapping all the registration133- methods for easy importing.134-135- This is available in `django.contrib.jinja` as `register`.136-137- For more details see the docstring of the `django.contrib.jinja` module.138- """139- def object(func, name=None):140- """Register a new global."""141- if name is None:142- name = getattr(func, '__name__')143- env.globals[name] = func144- return func145- object = staticmethod(object)146-147- def filter(func, name=None):148- """Register a new filter function."""149- if name is None:150- name = func.__name__151- env.filters[name] = func152- return func153- filter = staticmethod(filter)154-155- def test(func, name):156- """Register a new test function."""157- if name is None:158- name = func.__name__159- env.tests[name] = func160- return func161- test = staticmethod(test)162-163- def context_inclusion(func, template, name=None):164- """165- Similar to the inclusion tag from django this one expects func to be a166- function with a similar argument list to func(context, *args, **kwargs)167-168- It passed in the current context allowing the function to edit it or read169- from it. the function must return a dict with which to pass into the170- renderer. Normally expected is an altered dictionary.171-172- Note processors are NOT ran on this context.173- """174- def wrapper(env, context, *args, **kwargs):175- context = func(context.to_dict(), *args, **kwargs)176- return render_to_string(template, context)177- wrapper.jinja_context_callable = True178- if name is None:179- name = func.__name__180- try:181- wrapper.__name__ = func.__name__182- wrapper.__doc__ = func.__doc__183- except:184- pass185- env.globals[name] = wrapper186- context_inclusion = staticmethod(context_inclusion)187-188- def clean_inclusion(func, template, name=None, run_processors=False):189- """190- Similar to above however it won't pass the context into func().191- Also the returned context will have the context processors run upon it.192- """193- def wrapper(env, context, *args, **kwargs):194- if run_processors:195- request = context['request']196- else:197- request = None198- context = func({}, *args, **kwargs)199- return render_to_string(template, context, request)200- wrapper.jinja_context_callable = True201- if name is None:202- name = func.__name__203- try:204- wrapper.__name__ = func.__name__205- wrapper.__doc__ = func.__doc__206- except:207- pass208- env.globals[name] = wrapper209- clean_inclusion = staticmethod(clean_inclusion)deleted:jinja2/contrib/djangosupport.py-124 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja.contrib.djangosupport4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Support for the django framework. This module is quite magical because it7- just exports one single function, the `configure` function which is used8- to create a new Jinja environment and setup a special module called9- `django.contrib.jinja` which exports a couple of functions useful for Jinja.10-11- Quickstart12- ==========13-14- To get started execute the following code at the bottom of your settings.py15- or in some general application file such as urls.py or a central module. The16- only thing that matters is that it's executed right *after* the settings17- were set up and *before* `django.contrib.jinja` is imported::18-19- from jinja.contrib import djangosupport20- djangosupport.configure()21-22- What this does is setting up a Jinja environment for this django instance23- with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default24- django filters such as `date` and `timesince` which are not available in25- Jinja per default. If you want to change the list you can provide others26- by passing a list with filter import names as `convert_filters` keyword27- argument.28-29- All other keyword arguments are forwarded to the environment. If you want30- to provide a loader yourself pass it a loader keyword argument.31-32- Rendering Templates33- ===================34-35- To render a template you can use the functions `render_to_string` or36- `render_to_response` from the `django.contrib.jinja` module::37-38- from django.contrib.jinja import render_to_response39- resp = render_to_response('Hello {{ username }}!', {40- 'username': req.session['username']41- }, req)42-43- `render_to_string` and `render_to_response` take at least the name of44- the template as argument, then the optional dict which will become the45- context. If you also provide a request object as third argument the46- context processors will be applied.47-48- `render_to_response` also takes a forth parameter which can be the49- content type which defaults to `DEFAULT_CONTENT_TYPE`.50-51- Converting Filters52- ==================53-54- One of the useful objects provided by `django.contrib.jinja` is the55- `register` object which can be used to register filters, tests and56- global objects. You can also convert any filter django provides in57- a Jinja filter using `convert_django_filter`::58-59- from django.contrib.jinja import register, convert_django_filter60- from django.template.defaultfilters import floatformat61-62- register.filter(convert_django_filter(floatformat), 'floatformat')63-64- Available methods on the `register` object:65-66- ``object (obj[, name])``67- Register a new global as name or with the object's name.68- Returns the function object unchanged so that you can use69- it as decorator if no name is provided.70-71- ``filter (func[, name])``72- Register a function as filter with the name provided or73- the object's name as filtername.74- Returns the function object unchanged so that you can use75- it as decorator if no name is provided.76-77- ``test (func[, name])``78- Register a function as test with the name provided or the79- object's name as testname.80- Returns the function object unchanged so that you can use81- it as decorator if no name is provided.82-83- ``context_inclusion (func, template[, name])``84- Register a function with a name provided or the func object's85- name in the global namespace that acts as subrender function.86-87- func is called with the callers context as dict and the88- arguments and keywords argument of the inclusion function.89- The function should then process the context and return a90- new context or the same context object. Afterwards the91- template is rendered with this context.92-93- Example::94-95- def add_author(context, author=None):96- if author is not None:97- author = Author.objects.get(name=author)98- context['author'] = author99- return context100-101- register.context_inclusion(add_author, 'author_details.html',102- 'render_author_details')103-104- You can use it in the template like this then::105-106- {{ render_author_details('John Doe') }}107-108- ``clean_inclusion (func, template[, name[, run_processors]]) ``109- Works like `context_inclusion` but doesn't use the calles110- context but an empty context. If `run_processors` is `True`111- it will lookup the context for a `request` object and pass112- it to the render function to apply context processors.113-114- :copyright: 2007 by Armin Ronacher, Bryan McLemore.115- :license: BSD, see LICENSE for more details.116-"""117-try:118- __import__('django')119-except ImportError:120- raise ImportError('installed django required for djangosupport')121-else:122- from jinja.contrib._djangosupport import configure123-124-__all__ = ['configure']modified:jinja2/exceptions.py+2 added-2 removed
1 # -*- coding: utf-8 -*-2 """3- jinja.exceptions4- ~~~~~~~~~~~~~~~~3+ jinja2.exceptions4+ ~~~~~~~~~~~~~~~~~5 6 Jinja exceptions.7 8 :copyright: 2007 by Armin Ronacher.42 unmodified linesmodified:jinja2/filters.py+2 added-2 removed
1 # -*- coding: utf-8 -*-2 """3- jinja.filters4- ~~~~~~~~~~~~~3+ jinja2.filters4+ ~~~~~~~~~~~~~~5 6 Bundled jinja filters.7 8 :copyright: 2008 by Armin Ronacher, Christoph Hack.627 unmodified linesmodified:jinja2/tests.py+4 added-5 removed
1 # -*- coding: utf-8 -*-2 """3- jinja.tests4- ~~~~~~~~~~~3+ jinja2.tests4+ ~~~~~~~~~~~~5 6 Jinja test functions. Used with the "is" operator.7 8 :copyright: 2007 by Armin Ronacher.27 unmodified lines36 {% else %}37 variable is not defined38 {% endif %}39 40- See also the ``default`` filter.40+ See the ``default`` filter for a simple way to set undefined41+ variables.42 """43 return not isinstance(value, Undefined)44 45 34 unmodified lines80 81 {% if foo.attribute is sameas(false) %}82 the foo attribute really is the `False` singleton83 {% endif %}83-84- *New in Jinja 1.2*84 """85 return value is other86 87 10 unmodified linesmodified:jinja2/visitor.py+4 added-6 removed
10 unmodified lines11 from jinja2.nodes import Node12 13 14 class NodeVisitor(object):15- """16- Walks the abstract syntax tree and call visitor functions for every node17- found. The visitor functions may return values which will be forwarded18- by the `visit` method.15+ """Walks the abstract syntax tree and call visitor functions for every16+ node found. The visitor functions may return values which will be17+ forwarded by the `visit` method.18 19 Per default the visitor functions for the nodes are ``'visit_'`` +20 class name of the node. So a `TryFinally` node visit function would21 be `visit_TryFinally`. This behavior can be changed by overriding23 unmodified lines45 self.visit(node, *args, **kwargs)46 47 48 class NodeTransformer(NodeVisitor):50- """51- Walks the abstract syntax tree and allows modifications of nodes.49+ """Walks the abstract syntax tree and allows modifications of nodes.50 51 The `NodeTransformer` will walk the AST and use the return value of the52 visitor functions to replace or remove the old node. If the return53 value of the visitor function is `None` the node will be removed26 unmodified lines