2012-01-05 94 views
2

我有一个可以看作是单独页面或另一个页面(尽管ajax)的对象列表。Django通用ListView中的多个模板

因此,在我的模板中,我有一个“list_template.html”,它只有列表本身,当我在另一个页面中查看列表时使用该列表,而“full_list_template.html”扩展了基础模板并使用“include”标签在其中包含“list_template”。

我想在两种情况下使用相同的URL来获取项目列表。我还使用通用的ListView来显示对象列表。

几个问题:

1)它使用相同的URL这两种情况的好方法吗?

2)如果是,我怎么能有一个与ListView关联的URL,并根据“请求”更改template_name参数?

回答

4

是的,您可以在两种情况下使用相同的URL,并通过检查request.is_ajax()的值来设置相应的模板。现在不使用template_name类属性,而是覆盖get_template_names()方法(此方法应返回一个模板列表,将使用找到的第一个模板):

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