Home > Back-end >  How to use {{ url '' }} in HTML with a variable for the url reference
How to use {{ url '' }} in HTML with a variable for the url reference

Time:09-16

I'm working on a project to develop a wiki. I have a page with the list of entries, and I would like each of the entries to be clickable and redirect to the appropriate page.

HTML

<ul>
    {% for entry in entries %}
        <li><a href="{% url 'entry' %}">{{ entry }}</a></li>
    {% endfor %}
</ul>

The problem I'm facing is that I'm not sure how to put a variable inside my {% %} to get the href to point to the correct link. I'm not sure if it's helpful but here's the url parameterization as well:

urlpatterns = [
path("", views.index, name="index"), 
path("<str:entry>", views.markdown, name="entry"),
path("error", views.error, name="error")
]

CodePudding user response:

You can pass it as a positional or named parameter, so with:

<li><a href="{% url 'entry' entry=entry %}">{{ entry }}</a></li>

Note that you should place the error path before the entry path, otherwise error will be seen as an entry with as entry parameter 'error':

urlpatterns = [
    path('', views.index, name='index'),
    path('error/', views.error, name='error'),  # before entry
    path('<str:entry>/', views.markdown, name='entry')
]

CodePudding user response:

You can simply do by placing the variable after the url like this,

<ul>
    {% for entry in entries %}
        <li><a href="{% url 'entry' entry %}">{{ entry }}</a></li>
    {% endfor %}
</ul>
  • Related