2011-02-07 11 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 '' 

यह does not चर सेट के ट्रंक संस्करण का उपयोग कर रहा हूँ, लेकिन यह काम करता है अगर मैं @register.tag के साथ बहुत कुछ इसी तरह है, लेकिन वस्तु पैरामीटर में नहीं होता है ...

धन्यवाद!

उत्तर

18

आप यहां दो दृष्टिकोण जोड़ रहे हैं। एक simple_tag केवल एक सहायक कार्य है, जो कुछ बॉयलरप्लेट कोड पर कटौती करता है और एक स्ट्रिंग को वापस करने वाला माना जाता है। संदर्भ चर सेट करने के लिए, आपको रेंडर विधि के साथ write your own tag पर (सादा django के साथ) की आवश्यकता है।

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

+6

ध्यान दें कि Django के विकास के संस्करण भी शामिल है 'assignment_tag' जो' simple_tag' के समान है लेकिन 'variablename' के रूप में कार्यान्वित किया गया: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags –

+0

हू, मैं पहले कभी 'assignment_tag' भर नहीं पाऊंगा। निफ्टी। भविष्य के पाठकों के लिए एक अद्यतन: 'असाइनमेंट_टैग' Django संस्करणों> = 1.4 में उपयोग के लिए उपलब्ध है (जो मुझे लगता है कि ऊपर टिप्पणी करते समय देव में था)। – chucksmash

संबंधित मुद्दे