- September 27, 2008
- template template-tags template-engine
- 1 (after 1 ratings)
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.
Open the module
django.template.__init__, wherever that lives.
Scroll down to the beginning of "
Find the simple_tag function ("
Replace the function (even the whitespace before each line) with the code snippet.
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.
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, use
context['cheese'] = 'Limberger'. Due to the context's mutability, this will affect the context in the main template as well.
This code hasn't been tested in a "production environment", but I did test my modifications thoroughly, and if you don't add
simple_tag will behave exactly as normal. Of course, if there is a problem, make sure you leave a comment.
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 == '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
- testdata tag for templates by showell 6 years ago
- Paginator TemplateTag by trbs 7 years, 1 month ago
- Jinja2 integration + application specific functions/filters/tests by hasenj 6 years, 7 months ago
- Run Django as a FastCGI authorizer by cme 6 years, 6 months ago
- a simple tag with context by dsblank 5 years, 4 months ago