Question

I'm developing a custom Django template tag that requires multiple arguments. One of those arguments is a URL. When I try to do this:

{% my_tag arg1 {% url "myview" %} arg3=5 %}

I get the following template syntax error: Could not parse the remainder: '{%' from '{%'

How can I pass a URL to a custom template?

Was it helpful?

Solution

Simple url tag supports assignment.

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

OTHER TIPS

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 %}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top