2011-05-03 107 views
1

我想通過模板標籤將用戶對象傳遞給我的模板。我第一次嘗試simple_tag,但顯然它只適用於字符串?反正這是我到目前爲止有:用戶對象的Django模板標籤

templatetags/profiles.py

from django.template import Library, Node, Template, VariableDoesNotExist, TemplateSyntaxError, \ 
          Variable 
from django.utils.translation import ugettext as _ 
from django.contrib.auth.models import User 
from django.conf import settings 
from django.core.exceptions import ImproperlyConfigured 
from django.db import models 



class userlist(Node): 
    def __init__(self, format_string): 
     self.format_string = format_string 
    def render(self, context): 
     try: 
     users = self.format_string 
     return users 
     except VariableDoesNotExist: 
      return None 


def get_profiles(parser, token): 
    return userlist(User.objects.all()) 

register = Library() 
register.tag('get_profiles', get_profiles) 

這是我在我的模板來測試它:

{% load profiles %} 
{% get_profiles %} 
{% for p in get_profiles %} {{ p }} {% endfor %} 

我只得到[, , , , ]打印出來或者如果我將User.objects.all()更改爲User.objects.count(),我會得到正確的號碼。我的模板中的迭代似乎沒有做任何事情。哪裏不對?

+0

User.objects.get(用戶名=「測試」)給我的用戶「測試」正確也。正當我嘗試傳遞所有對象並迭代時,我不會在模板中獲取任何與循環有關的東西。 – leffe 2011-05-03 14:52:32

回答

0

什麼是格式字符串?你需要調用模板標籤是這樣的:

{% get_all_users as allusers %} 
{% for user in allusers %} 
    {{ user.first_name }} 
{% endfor %} 

所以你需要一個模板標籤一樣

class GetAllUsers(Node): 
    def __init__(self, varname): 
     # Save the variable that we will assigning the users to 
     self.varname = varname 
def render(self, context): 
     # Save all the user objects to the variable and return the context to the template 
     context[self.varname] = User.objects.all() 
     return '' 

@register.tag(name="get_all_users") 
def get_all_users(parser, token): 
    # First break up the arguments that have been passed to the template tag 
    bits = token.contents.split() 
    if len(bits) != 3: 
     raise TemplateSyntaxError, "get_all_users tag takes exactly 2 arguments" 
    if bits[1] != 'as': 
     raise TemplateSyntaxError, "1st argument to get_all_users tag must be 'as'" 
    return GetAllUsers(bits[2]) 
+0

{%get_all_users as alluserrs%} 這給了我一個Caught TypeError而渲染:不可用類型:'列表'。我在{get_all_users%} {{user}} {%endfor%}中嘗試了{%。它不會抱怨,但它也不會打印任何東西。 – leffe 2011-05-04 07:41:19

+0

謝謝你的幫助!我不得不改變返回GetAllUsers(bits) 返回GetAllUsers(bits [2]),否則它是完美的。再次感謝! – leffe 2011-05-04 08:52:24

+0

啊是啊,編輯帖子反映! – 2011-05-04 08:58:22