2010-04-12 35 views
4

試圖解決模板標籤問題。For template variable中使用的循環變量?

我有兩個templatetags:

@register.inclusion_tag('directory/_alphabet.html') 
def alphabet_list(names): 
    """ Return a list of letters that last names start with. """ 
    return { 'letters': [name.last_name[0] for name in names] } 

class NameNode(template.Node): 
    def __init__(self, letter, var_name): 
     self.letter = letter 
     self.var_name = var_name 

    def render(self, context): 
     context[self.var_name] = Person.objects.get_active().filter(
      last_name__istartswith=self.letter) 
     return '' 

@register.tag 
def get_names(parser, token): 
    try: 
     tag_name, arg = token.contents.split(None, 1) 
    except ValueError: 
     raise template.TemplateSyntaxError, "%r tag requires arguments" % \ 
       token.contents.split()[0] 
    m = re.search(r'for (.*?) as (\w+)', arg) 
    if not m: 
     raise template.TemplateSyntaxError, "%r tag had invalid arguments" % \ 
       tag_name 
    letter, var_name = m.groups() 
    return NameNode(letter, var_name) 

而且我想使用它們像這樣:

{% for letter in letters %} 
<h2>{{ letter }}</h2> 
{% get_names for letter as names %} 
<ul> 
    {% for name in names %} 
    <li>{{ name }}</li> 
    {% endfor %} 
</ul> 
{% endfor %} 

但「信」被髮送的字「信」而不是什麼信變量應該包含。有沒有辦法解決這個問題或者我錯過了什麼(或者更好的是,一個已經這樣做的包)?

回答

4

您得到字符串"letter",因爲這是模板解析器從您的模板源讀取的內容。如果要訪問此變量的值,則必須將其標記爲NameNode.__init__中的模板變量,並使用render中的上下文來解析

如下:

class NameNode(template.Node): 
    def __init__(self, letter, var_name): 
     self.letter = template.Variable(letter) 
     self.var_name = var_name 

    def render(self, context): 
     try: 
      context[self.var_name] = Person.objects.get_active().filter(
       last_name__istartswith=self.letter.resolve(context)) 
     except template.VariableDoesNotExist: 
      pass 
     return '' 

它在文檔here解釋。

+0

謝謝。我閱讀這些文檔,但錯過了.resolve()部分。 – kennethlove 2010-04-12 20:55:25