Baskaya
Baskaya

Reputation: 7841

How can I call a filter with more than one argument?

I need to call a filter with more than one argument.

If a filter takes only one parameter, for example "cut", we can call it with

{{ somevariable|cut:"0" }}

But if I create a custom filter which takes two parameters, I cannot call it with correct syntax.

For answers, I ask this only:

I think calling with two arguments is legal because there is a default filter named urlizentrunc.

def urlizetrunc(value, limit, autoescape=None):

Upvotes: 3

Views: 9685

Answers (2)

Spycho
Spycho

Reputation: 7788

You cannot. The only work-arounds are to pass in one parameter and parse it into parts, or to have a variable external to the filter passed in.

The docs state that it cannot be done with custom filters. See this question for a more detailed explanation.

You cannot directly pass multiple parameters to non-custom filters, such as urlizetrunc either. urlizetrunc takes one parameter from the template. autoescape is set in by calling the autoescape tag with a parameter of "off" or "on". When you call urlizetrunc from the template, it passes in whatever value autoescape has been set to. You cannot pass in the value of autoescape directly from the template. See this question for a more detailed explanation.

Upvotes: 3

Drekembe
Drekembe

Reputation: 2716

You'll have to settle for taking one argument and then parsing it. The autoescape parameter is kind of special because it's there in cases your filter needs to know whether autoescaping is on or off. For more info, check out this link: https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#filters-and-auto-escaping

But parsing the argument in your custom filter isn't that hard, usually it's just doing argument.split(" ") or argument.split(",")

Upvotes: 1

Related Questions