Conditional display or loading in Django

Published on: (Updated on: )
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.