Home > OS >  Django: How to pass {% url 'event_manager:index' %} to template component?
Django: How to pass {% url 'event_manager:index' %} to template component?

Time:03-06

So right now I hardcode to url, which is a bit annoying if you move endpoints. This is my current setup for my navbar items.

# in base.html

{% include 'components/navbar/nav-item.html' with title='Event Manager' url='/eventmanager/' %}
# in components/navbar/nav-item.html

<li>
  <a href="{{ url }}">{{ title }}</a>
</li>

See how I use the url right now?

What I now want is this:

{% include 'components/navbar/link.html' with title='Event Manager' url={% url 'event_manager:index' %} %}

But apparently, this is invalid syntax. How do I do it?

If it is not possible, how do I create an app that somehow creates a view where I can pass all the URLs with context variable? In theory, this sounds easy but I'd have to somehow insert that view in every other view.

CodePudding user response:

You can pass it as a variable not django's url tag, use like this:

{% url 'event_manager:index' as myurl %}
{% include 'components/navbar/link.html' with myurl %}

Now you can pass it to include tag.

CodePudding user response:

My solution which fixed it:

# navbar.html

{% include 'components/navbar/nav-item.html' with title='Event Manager' to_url='event_manager:index' %}
# nav-link.html

{% url to_url as myurl %}

<li>
  <a href="{{ myurl }}">{{ title }}</a>
</li>
  • Related