Is conditional rendering good in django?

Viewed 52

I don't know if conditional rendering a whole HTML template is good or bad? I understand that we can do this on templates but just wanna know if this is okay?

In my view,

if profile.exists():
        return render(request, 'index.html')
    else:
        return render(request, 'nodata_index.html')

Is this good, or shall I do if template condition on templates? Is there any problem using the above method or shall go with template formats

1 Answers

You can't find an overall rule for this but I would suggest the following:

  • If your condition will lead to totally different layouts, then just do it in the view and choose the template there.

  • If your condition only changes parts of a template, then do it in your template.

It's also a good practice to create small parts of a template in different files and include them when needed which helps your template files be more readable.

Don't create many templates that look basically the same but with small differences but rather create a parent template and include the small parts in the parent.

Related