site logo

Stacknatic

Stacknatic logo

We Care About Your Privacy

Stacknatic utilizes technologies, such as cookies, to enhance your browsing experience. By using this technology, you can be provided with a more personalized and seamless interaction with this website. By continuing, you agree with the Privacy Policy of Stacknatic.

Privacy Policy | Terms of Use
Home/blog/Conditional display or loading in Django

Conditional display or loading in Django

featured image for Conditional display or loading in Django

Published on: June 9, 2023 (Updated on: July 14, 2024)

Sometimes you might want to display content or load content conditionally based on a page in Django. This post will show you how to achieve it. Knowing how to display content conditionally is a very useful skill for any developer. This would enable you to optimize your pages and ultimately create fast loading pages.

An example of a use case is where you have several JavaScript source files in your base.html and it would be unnecessary to load them all on every page of your website.

Suppose you have the following in your base.html:

<script src="main.js"></script>
<script src="blog.js"></script>
<script src="form.js"></script>
<script src="polls.js"></script>

If for instance you want to load polls.js only on polls pages, you can modify your code as follows:

​<script src="main.js"></script>
<script src="blog.js"></script>
<script src="form.js"></script>
{% if 'polls' in request.path %}
<script src="polls.js"></script>
{% endif %}

The result is that your polls.js will now only load on the relevant pages where it is needed.

See more posts in Websites
Author:author's avatarMichael Akerele