Search code examples
pythondjangodjango-templatestags

django custom template tag, pass multiple arguments


I need to be able to pass multiple parameters to a custom template tag. I dont know how to do it but I've seen an example like this somewhere. If you got the idea, is it possible to do it in some way?

template
{% for right in people_rights|user_available_rights:rooms, user.id %}
   {{right.room}}
{% endfor %}

template tag
def user_available_rights(rights, rooms, user_id):

    available_rights = []
    user_rooms = []

    for right in rights:
        if right.user.id == user_id:
            user_rooms.append(right.room)

    for room in rooms:
        for ur in user_rooms:
            if room.id != ur.id:
                available_rights.append(room)

    return available_rights


Solution

  • You can pass multiple arguments to your custom tag by using simple_tag like this:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def tag_name(arg1, arg2, arg3):
       return 
    

    Then you can use this tag in your template by

    {% tag_name 'foo' 'bar' 'baz' %}