2011-02-07 7 views
9

私はsimple_tagを使ってコンテキスト変数を設定しようとしています。私は、このdoesntのは、変数を設定するが、私は@register.tagと非常に似た何かをする場合、それは動作しますが、オブジェクトパラメータが通過しないDjangoの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 '' 

のジャンゴのトランクバージョンを使用しています...

感謝を!

答えて

18

ここでは2つのアプローチを混在させています。 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

おかげで、あなたは答えはジャンゴの開発版は 'simple_tag''に似てassignment_tag'が含まれていることを – neolaser

+6

注感謝完璧とずっとでしたよしかし、 'as variablename'が実装されています:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags –

+0

ああ、私は決して前に' assignment_tag'を越えて走ってはいけません。ニフティ。将来の読者のためのアップデート: 'assignment_tag'は、Djangoバージョン> = 1.4で使用できるようになりました(これは、上記のコメントが作成された時のdevだと思います)。 – chucksmash

関連する問題