How to Render Different Templates Based on a Condition in Django



Python


In this article, we go over how to render different templates based on a condition in Django.

So, based on a certain condition, we may want to render a certain template if one condition is true and render another template if another condition is true.

So how do we render different templates based on a condition in Django?

We can use if statements and set the template variable to a different template in the if conditional statement.

So an example code is shown below.



So the above is our code.

from django.shortcuts, we import render

render is need to render our template file.

We then have our function, showview().

As always, we pass in the request object.

We then set up a conditional statement consisting of an if-else statment to see whether a user is logged in or not.

If a user is logged in, the template variable is set to, "Blog/logged_in_template.html"

If a user is not logged in, the template variable is set to, "Blog/public_template.html"

Thus, we can render different templates based on this condition.

So Django can be very dynamic in that it can render different templates based on a condition.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...