2011-02-07 13 views
9

Im tratando de usar un simple_tag y establecer una variable de contexto. Estoy utilizando la versión maletero de DjangoDjango simple_tag y configuración de variables de contexto

from django import template 

@register.simple_tag(takes_context=True) 
def somefunction(context, obj): 
    return set_context_vars(obj) 

class set_context_vars(template.Node): 
    def __init__(self, obj): 
     self.object = obj 

    def render(self, context): 
     context['var'] = 'somevar' 
     return '' 

ésto no establece la variable, pero si hago algo muy similar con @register.tag que funciona, pero el parámetro objeto no pasa por ...

Gracias!

Respuesta

18

Aquí está mezclando dos enfoques. Un simple_tag es simplemente una función de ayuda, que reduce un código repetitivo y se supone que devuelve una cadena. Para establecer variables de contexto, necesita (al menos con django simple) a write your own tag con un método de renderizado.

from django import template 

register = template.Library() 


class FooNode(template.Node): 

    def __init__(self, obj): 
     # saves the passed obj parameter for later use 
     # this is a template.Variable, because that way it can be resolved 
     # against the current context in the render method 
     self.object = template.Variable(obj) 

    def render(self, context): 
     # resolve allows the obj to be a variable name, otherwise everything 
     # is a string 
     obj = self.object.resolve(context) 
     # obj now is the object you passed the tag 

     context['var'] = 'somevar' 
     return '' 


@register.tag 
def do_foo(parser, token): 
    # token is the string extracted from the template, e.g. "do_foo my_object" 
    # it will be splitted, and the second argument will be passed to a new 
    # constructed FooNode 
    try: 
     tag_name, obj = token.split_contents() 
    except ValueError: 
     raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0] 
    return FooNode(obj) 

Esto se puede llamar así:

{% do_foo my_object %} 
{% do_foo 25 %} 
+0

gracias, eres respuesta fue perfecta y muy apreciado – neolaser

+6

Tenga en cuenta que la versión de desarrollo de Django incluye 'assignment_tag' que es similar a' simple_tag' pero con 'as variablename' implementado: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags –

+0

Huh, nunca me hubiera encontrado con' assignment_tag' antes. Hábil. Una actualización para futuros lectores: 'assignment_tag' está disponible para su uso en las versiones de Django> = 1.4 (que supongo que estaba en dev cuando se realizó el comentario anterior). – chucksmash

Cuestiones relacionadas