2011-02-07 79 views
9

我試圖使用simple_tag並設置上下文變量。我現在用的主幹版本的DjangoDjango simple_tag和設置上下文變量

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 '' 

這並不設定的變量,但如果我做@register.tag非常類似的東西它的工作原理,但對象參數沒有通過......

謝謝!

回答

18

你在這裏混合兩種方法。 A simple_tag僅僅是一個幫助函數,它可以減少一些樣板代碼,並且應該返回一個字符串。要設置上下文變量,你需要(至少用普通的django)到write your own tag的渲染方法。

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) 

這可以被稱爲是這樣的:

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

感謝,你的答案是完美的,非常感謝 – neolaser 2011-02-07 03:08:45