2

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 %}
2
  • Can you give an example of how you want to use them? Commented Jul 19, 2019 at 9:29
  • @alias51 you can manipulate the urls on views and pass it to template as list. Commented Jul 19, 2019 at 9:46

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.