Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - use filter in the argument to a simple_tag

Tags:

python

django

I had a custom simple-tag. And it seems I can't use a filter as its argument.

Here is an example. mysum is the tag. myincrease is the filter. foobar is a variable and I want to pass foobar|myincrease to mysum.

The template:

{% mysum foobar|myincrease 1 2 %}

gives the error:

TemplateSyntaxError at /

Caught VariableDoesNotExist while rendering: Failed lookup for key [foobar|myincrease] in ...

The tag:

@register.simple_tag
def mysum(a, b, c):
    return a + b + c

The filter:

@register.filter
def myincrease(num):
    return num + 1

I have worked around my original problem using other approaches. But I'm still wondering if this is by design, or a mistake of mine, or a bug of django, or something that has been overlooked.

I think calling something like compile_filter in the simple_tag decorator implementation would do it.

like image 526
jsz Avatar asked Nov 13 '22 16:11

jsz


1 Answers

Though it doesn't appear to be mentioned in the ticket, it looks like the fixing of https://code.djangoproject.com/ticket/13956 added filter support to positional arguments to a tag. You can see the commit at https://github.com/django/django/commit/8137027f - the new parse_bits function called compile_filter() on positional arguments.

Another workaround would be to use the {% with %} tag.

like image 62
M Somerville Avatar answered Dec 24 '22 08:12

M Somerville