Wednesday, March 30, 2011

Re: django custom template tags: how to send to (parser, token)

On 30 mar, 21:55, justin jools <justinjo...@gmail.com> wrote:
> I've just started using custom tags and need some help parsing info
> to:
>
> @register.tag
> def friends_of(parser, token):
>     tag_name, user_var = token.split_contents()

Don't assume you'll only have what you expected here. The canonical
form would be:

args = token.split_contents()
tag_name = args.pop(0)

if len(args) > 1:
raise TemplateSyntaxError("some useful message here")

>     return FriendsOfNode(user_var)
>
> class FriendsOfNode(template.Node):
>     def __init__(self, user_var):
>         self.user_var = template.Variable(user_var)
>
>     def render(self, context):
>         user = self.user_var.resolve(context)
>         context.update({'friends': Friendship.objects.friends_of(user,
> True)})
>         return u''
>
> I tried:
>
> friends: {% friends_of {{ user }} %}

This should be {% friends_of user %}. The {{ varname }} syntax is only
for value substitution in the template itself, not for templatetags.

Also and as a side note, when using a template tag to populate the
context, it's better to give a way to specify the var name under which
the value(s) will be available, ie:

{% friends_of user as whatever %}

(which will of course require a bit more parsing...)

>
> output:
>
> ValueError at /friends/
>
> too many values to unpack

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment