2011-02-07 2 views
9

나는 simple_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 '' 

의 트렁크 버전을 사용하고 있습니다,하지만 난 @register.tag와 매우 비슷한 뭔가를 할 경우는 작동하지만 object 매개 변수가 통과하지 않습니다!

답변

18

두 가지 접근 방법을 혼합합니다. simple_tag은 단순한 헬러 함수이며, 일부 상용구 코드를 줄이고 문자열을 반환해야합니다. 컨텍스트 변수를 설정하려면 render 메서드를 사용하여 적어도 일반 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

관련 문제