Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use a django variable in an <a> tag's href?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading