2

Why can't I type this in a Django template?

data|customTag:variable,forloop.parentloop.counter

I just want to be able to pass three or more arguments into a filter

pretend there are already for loop and the variable/filter have been defined elsewhere

Jeremy
  • 1,717
  • 5
  • 30
  • 49

2 Answers2

1

This is not possible since django template filters accept only one argument by definition:

Custom filters are just Python functions that take one or two arguments:

  • The value of the variable (input) – not necessarily a string.

  • The value of the argument – this can have a default value, or be left out altogether.

There is a workaround suggested here that might work for your use case.

Another possible solution would be to split your tag with 2 input arguments into two tags with a single one and chain them in the template. It depends on the logic you have in the filter, but can be an option.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

In your example, customTag is a filter, not a template tag.

According to the docs, Django template filters only take the input (in your case data), and one optional argument. You are getting the error because you are trying to pass more than one argument, which is not possible.

You could write a custom template tag instead. The syntax in your template would be:

{% customTag data variable forloop.parentloop.counter %} 
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • I've decided to use this route. how would I actually pass in the context of data? because right now it just sends the string 'data'. and {{data}} just passes '{{data}}' – Jeremy Jan 08 '15 at 02:29
  • This is completely useless if I can't figure out how to pass in a variable... I tried reading the source code at defaulttags.py and I can't figure it out – Jeremy Jan 08 '15 at 03:00
  • If you use the [`simple_tag`](https://docs.djangoproject.com/en/1.7/howto/custom-template-tags/#simple-tags) decorator it should take care of this for you. Otherwise, you can fetch the variable out the `context`. – Alasdair Jan 08 '15 at 12:05