[Django]-Pass {% url %} to custom template tag in Django

7👍

Simple url tag supports assignment.

{% url 'myview' as my_url %}
{% my_tag arg1 my_url arg3=5 %}

3👍

In case anyone really does want to get this working without having a lot of junk in thier templates I found that you can simply use django.urls.reverse in your tag function

For example in your tag function:

from django.urls import reverse

@register.simple_tag
def my_tag(arg1, url, arg3 = None, *args, **kwargs):
    # resolve the url (you don't have to pass both args and kwargs, it's up to you.)
    resolved_url = reverse(url, None, args, kwargs)
    # do whatever you have to do
    pass

In your template simply pass the string that you would pass like {% url 'myview' %}:

{% my_tag arg1 'myview' arg3=5 %}

or

{% my_tag arg1 'myapp:myview' arg3=5 %}

by passing the args and/or kwargs along you can pass additional params to reverse (like a primary key for example).

{% # here the article.pk is passed to reverse # %}
{% my_tag arg1 'myapp:myview' arg3 article.pk %}
👤Goran

Leave a comment