I want to create a list
of entries in which each entry is linked to its page like this: wiki/entry-title
. I'm using a for
loop to add <li>
s to HTML. here's the code:
<ul>
{% for entry in entries %}
<li><a href="">{{ entry }}</a></li>
{% endfor %}
</ul>
urlpattern:
path('wiki/<str:title>', views.entry, name='entry')
what should I type in href
to link the <li>
to wiki/entry
?
CodePudding user response:
You can set your value in url as
<ul>
{% for entry in entries %}
<a href="/wiki/{{entry.value}}"><li>{{ entry }}</li></a>
{% endfor %}
</ul>
Its better to use {% url %} [Django-doc] template tags as
<ul>
{% for entry in entries %}
<a href="{% url 'your-url-name' entry.value %}"><li>{{ entry }}</li></a>
{% endfor %}
</ul>
NOTE : change value
with your value accordingly. For e.g. {{entry.value}}
or {{entry.title}}
or {{entry.id}}
CodePudding user response:
There is a clear example in the django docs
<ul>
{% for yearvar in year_list %}
<li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>
CodePudding user response:
In django, the template parser always handles django code first, then html/javascript. So you would insert a django variable into an anchor tag the same way you'd insert it anywhere in the template and the parser will replace it before it tries to render the html. If it's a django url, you can use the {% %}
format as referenced in the previous answer, and if it's a url that's perhaps stored on the object, you can just use {{ }}
(like {{ entry.wiki_url }}
). You can also use text for some of the url and a variable for part. So if you have a wiki site that has a base url of, for instance, https://mywiki.com
you'd write the href like:
<ul>
{% for entry in entries %}
<a href="https://mywiki.com/{{entry.title}}"><li>{{ entry.title }}</li></a>
{% endfor %}
</ul>