duduklein
duduklein

Reputation: 10604

Multiple Templates in Generic ListView in Django

I have a list of objects that can be seen as a separate page or within another page (though ajax).

So, in my templates, I have a "list_template.html" that only has the list itself, which I use when I'm viewing the list within another page and a "full_list_template.html", which extends the base template and use the "include" tag to include the "list_template" in it.

I would like to use the same URL to get the list of items in both situations. I'm also using a generic ListView to show the list of objects.

Few questions:

1) is it a good approach to use the same URL for both situations?

2) if yes, how can I have one URL associated with a ListView and change the template_name parameter according to the "request"?

Upvotes: 4

Views: 1181

Answers (1)

brutasse
brutasse

Reputation: 819

Yes, you can use the same URL for both situations and set the appropriate template by checking the value of request.is_ajax(). Now instead of using the template_name class attribute, override the get_template_names() method (this method should return a list of templates, the first one found will be used):

class MyView(ListView):
    def get_template_names(self):
        if self.request.is_ajax():
            return ['list_template.html']
        return ['full_list_template.html']

Upvotes: 7

Related Questions