Django Templatetag与用户对象

时间:2011-05-03 14:00:27

标签: django django-templates

我正在尝试通过templatetag将用户对象传递给我的模板。我首先尝试过simple_tag,但显然它只适用于字符串?无论如何,这是我到目前为止:

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(),我会得到正确的号码。我的模板中的for迭代似乎没有做任何事情。怎么了?

1 个答案:

答案 0 :(得分: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])