6

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?

2
  • 2
    In addition to Luke's good suggestion of using Variable.resolve, I also found another simple solution. Setting context=True as an argument in the inclusion tag decorator adds the context of the current view as a dictionary. You can then access the attr of the context object--context['variable']. It effectively looks like this: @register.inclusion_tag("template-to-include", takes_context=True) Commented May 18, 2011 at 14:29
  • The takes_context=True method ended up being the solutions for me. Note that you also need to have context as your first arg to the inclusion tag. I think you should make a separate answer for your solutions. Thanks! Commented Oct 13, 2017 at 9:06

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hey Luke, your suggestion worked great. I also found another solution to this problem that's pretty simple. See my comment above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.