如何在Django DetailView中根据条件渲染模板

时间:2019-05-14 06:09:40

标签: django

我尝试覆盖get_templates_name()。但这无济于事。

def get_template_names(self):
    theme = Themes.objects.filter(theme_creator=self.request.user)
    for t in theme:
        if t.technology_theme == True:
            return ["landing/preview/preview1.html/"]       
        elif t.default_theme == True:
            return  ["landing/categories/technology/technology1.html/"]

2 个答案:

答案 0 :(得分:1)

初始化一个变量,如

 if t.technology_theme == True:
     template_name = "landing/preview/preview1.html"
 elif t.default_theme == True:
     template_name = "landing/categories/technology/technology1.html"

并返回template_name形成您的视图,例如

在CBV中:

template_name=template_name

在FBV中:

retrun render(request, template_name, context)

答案 1 :(得分:0)

在get_object()或get_context_data()中,您可以定义模板名称,如下所示:

def get_context_data(self, **kwargs):
    context = super(YourView, self).get_context_data(**kwargs)
    self.template_name = 'your_template.html'
    return context