alias51
alias51

Reputation: 8608

How to loop through urls in a template

I have a load of URLs I want to declare as constants so I can use them in for and if statements in a template. At the moment I do this manually e.g.:

{% url 'inbox' as inbox %}
{% url 'sent' as sent %}
{% url 'drafts_tasks' as drafts_tasks %}

However this feels kinda clunky and when the urls increase in numbers it is a load of extra code repeated on every template.

Is there a better way I can loop through urls and declare them?

Here's an example of how I want to use them:

{% url 'XXX' as XXX %}
{% for ....

        <li class="nav-item {% if request.path == XXX %}active{% endif %}">
            <a class="nav-link" href="{{ XXX.url }}">{{ XXX.name }}
            </a>
        </li>

endfor %}

Upvotes: 2

Views: 652

Answers (1)

bdoubleu
bdoubleu

Reputation: 6107

The easiest option would be to pass the urls as a list.

class URLView(TemplateView):
    template_name = 'urls.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['urls'] = get_my_list_of_urls()
        return context

As for the repeated code you could make use of the include template tag.

Create a file with the repeating template fragment templates/includes/url_link_list.html:

<li class="nav-item {% if request.path == xxx %}active{% endif %}">
    <a class="nav-link" href="{{ xxx.url }}">{{ xxx.name }}</a>
</li>

Then in your urls.html file that was defined in your view you will include that fragment:

<ul>
    {% for url in urls %}
        {% with url as xxx %}
            {% include 'includes/url_link_list.html' %}
        {% endwith %}
    {% endfor %}
</ul>

Upvotes: 1

Related Questions