Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Custom Template Tag with Context Variable Argument

I have a custom template tag which shows a calendar. I want to populate certain items on the calendar based on a dynamic value.

Here's the tag:

@register.inclusion_tag("website/_calendar.html")
def calendar_table(post):
     post=int(post)
     imp=IMP.objects.filter(post__pk=post)
     if imp:
         ...do stuff

In my template, it works fine when I pass a hard coded value, such as

    {% load inclusion_tags %}

    {% calendar_table "6" %}

However when I try something like {% calendar_table "{{post.id}}" %} , it raises a error a ValueError for the int() attempt. How can I get around this?

like image 782
Ben Avatar asked May 17 '11 22:05

Ben


1 Answers

You want {% calendar_table post.id %}; the extra {{ and }} are what are causing you the heartburn.

Note that, in your custom tag, you need to take the string ("post.id") that gets passed and resolve it against the context using Variable.resolve. There's more information on that in the Django docs; in particular, look here: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag

like image 198
Luke Sneeringer Avatar answered Sep 21 '22 00:09

Luke Sneeringer