What is the correct assignment of context variables in the navigation bar? My Django example is:
in view.py:
from django.shortcuts import render
from django.http import HttpResponse
context_navigation = {
'Link1' : 'Blog',
'href1' : "{% url 'blog' %}", }
def index(request):
return render(request, 'app_about/index.html', context=context_navigation)
in urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('blog/', views.index, name='blog'),
]
in templates/base.html this does work
<a class="nav-item nav-link text-light" href="{% url 'blog' %}" > {{Link1}}</a>
this does not work (see href1
and Link1
)
<a class="nav-item nav-link text-light" href="{{href1}}" > {{Link1}}</a>
In the last case a wrong url is generated, something like http://127.0.0.1:8000/blog/%7B%
.
What is the correct assignment of href
as a context variable href1
? Thank you for some hints!
In the second example you insert a variable href1
, which is replaced by the content (the string) {% url 'blog %}
when rendered. Django trys to render this string (makes it html safe, thats where the %7B
.. came from, which is just the html code for {
.
You can either resolve the url using python in the view and pass the actual url as string to the template:
views.py
from django.urls import reverse
context_navigation = {
'Link1' : 'Blog',
'href1' : reverse('blog')
}
base.html
<a class="nav-item nav-link text-light" href="{{href1}}">{{Link1}}</a>
Or you go with the first example, where {% url 'blog %}
will be interpreted and executed by the template rendering engine:
context_navigation = {
'Link1' : 'Blog'
}
base.html
<a class="nav-item nav-link text-light" href="{% url 'blog' %}">{{Link1}}</a>
If you need to generate the context dynamically but want to resolve the actual urls in the template you can maybe pass the url name as variable like:
context_navigation = {
'Link1': 'Blog',
'url1': 'blog',
}
base.html
<a class="nav-item nav-link text-light" href="{% url url1 %}">{{Link1}}</a>
But I'm not sure if you can use varaibles in template tags like this (just a guess, never used it this way)