简体   繁体   中英

How to have two arguments in a django custom filter

I am trying to manipulate two objects for a calculation, however I am getting the error:"Invalid filter"

In the html frontend I have a nested loop with objects: units and person as following:

{{units|myFilter:person}}

where units has several objects and person only has one.

my filter is defined by:

def myFilter(units,person):
    n = 0
    for i in units:
        if i.name == person.name:
            n = n + 1
    return n

But is it not working, any ideas or suggestions please?

You can register a simple_tag function which accepts any number of positional or keyword arguments;

from django import template

register = template.Library()

@register.simple_tag
def my_tag(a, b):
    print(a, b)

    return 'What you need'

And this is how to use it in your template;

{% my_tag 123 "abcd" %}

Here is the documentation; https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/#simple-tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM