This is a mod I made to the Django simple_tag system to let the simple_tags access comments. I plan to try and get it integrated into the trunk, so it's mainly here so (a) the people on django-developers can see it, and (b) while I'm waiting, or if it doesn't get put in the trunk, people can use it.
Installing
-
Open the module
django.template.__init__
, wherever that lives. -
Scroll down to the beginning of "
class Library:
" -
Find the simple_tag function ("
def simple_tag(self,func):
") -
Replace the function (even the whitespace before each line) with the code snippet.
Usage
-
When defining a simple tag (see the docs for more info), have the first parameter in your function be named "
context
". Otherwise, an error will be thrown. It can accept other parameters like normal. -
Use
register.simple_tag(my_function_name, takes_context=True)
to register your function as one that will use the context. -
The tag's function can access the context like a dictionary - to get a value, just use
context['cheese']
, or to set one, usecontext['cheese'] = 'Limberger'
. Due to the context's mutability, this will affect the context in the main template as well.
Notes
This code hasn't been tested in a "production environment", but I did test my modifications thoroughly, and if you don't add takes_context=True
, simple_tag
will behave exactly as normal. Of course, if there is a problem, make sure you leave a comment.
Code
Since most of the code is hacked up from other Django library functions, and to prepare for if and when it's merged into the trunk, it's released under the BSD license.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | def simple_tag(self,func,takes_context=False):
params, xx, xxx, defaults = getargspec(func)
if takes_context:
if params[0] == 'context':
params = params[1:]
else:
raise TemplateSyntaxError("Any tag function with takes_context set must have a first argument of 'context'")
class SimpleNode(Node):
def __init__(self, vars_to_resolve):
self.vars_to_resolve = map(Variable, vars_to_resolve)
def render(self, context):
resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
if takes_context:
return func(context, *resolved_vars)
else:
return func(*resolved_vars)
compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, SimpleNode)
compile_func.__doc__ = func.__doc__
self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
return func
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.