How to do reverse URL with keyword argument in Jinja2?
In a view function we can do the following:
from django.http import HttpResponseRedirect
from django.urls import reverse
def SomeView(request):
return HttpResponseRedirect(
reverse('blog:specific-topic', kwargs={'topic':'python'})
)
In a template, without keyword argument, we can do this:
<a href="{{ url('home-page') }}">Home Page</a>
But how to do reverse URL in Jinja2 with keyword arguments?
I am developing a programming blog, so I need to organize articles into topics including Python, Dajngo, Jinja2, Designing Relational Databases, and so forth. I wrote the following:
<a href="{{ url('blog:specific-topic', topic.slug) }}" class="topic">{{ topic.name }}</a>
But it did not work.
I found how to do it. First of all create a dictionary and add key-value pairs to it like Python syntax:
{% set kwargs_ = dict(topic_slug=article.topic.slug, article_slug=article.slug) %}
Then pass this dictionary to kwargs argument of reverse (in Jinja2 usually url) function:
<a href="{{ url('blog:specific-topic', kwargs=kwargs_) }}" class="topic">{{ topic.name }}</a>
And it works.