Login

Mod to allow simple_tag to access context

Author:
leaf
Posted:
September 27, 2008
Language:
Python
Version:
1.0
Score:
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.

Installing

  1. Open the module django.template.__init__, wherever that lives.

  2. Scroll down to the beginning of " class Library: "

  3. Find the simple_tag function (" def simple_tag(self,func): ")

  4. Replace the function (even the whitespace before each line) with the code snippet.

Usage

  1. 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.

  2. Use register.simple_tag(my_function_name, takes_context=True) to register your function as one that will use the context.

  3. 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.

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.