python - Django 动态更改 get_context_data 中的 template_name
问题描述
如何根据上下文覆盖template_name
a ?换句话说,我想找到一种方法来根据我的上下文更改呈现的模板。TemplateView
get_context_data
以下是从我当前的代码修改的,它不起作用:
class FooPage(TemplateView):
template_name = "folder/template1.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable
if "text" in context['myvariable']:
template_name = "folder/template2.html" # This line does get executed
return context
我可以确认换行template_name
已执行,并且确实设置"folder/template2.html"
为该点,但是呈现的实际页面仍然看起来像原始的 ( template1.html
) 。
任何有用的见解将不胜感激。非常感谢!
解决方案
当你写:
template_name = "folder/template2.html"
您只是在声明一个永远不会被使用的局部变量。相反,您想修改可以通过以下方式访问/修改的实例变量self
:
class FooPage(TemplateView):
template_name = "folder/template1.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable
if "text" in context['myvariable']:
self.template_name = "folder/template2.html"
return context
推荐阅读
- sorting - 从 Firestore (Vue.js) 获取数据的错误顺序
- google-bigquery - BigQuery - 在使用具有不同数据类型的 UNION ALL 和 STRUCT 时无法使用 DISTINCT
- jsf - 键入时更新 p:inputText 样式
- c# - .Net 和 dotnet Core 之间的 GZipCompress 差异
- javascript - 元素名称中的点是什么意思?
- javascript - 如何跟踪所有用户对 Jira 网站按钮的点击次数
- javascript - 在打字稿中交换多维数组中的元素
- jupyter-notebook - 将虚拟环境添加到 conda 后,无法打开打开的 jupyter 笔记本。为什么?
- ios - Unity iOS 构建失败:Xcode 中语音识别的重复符号
- solr - Hue Solr 标记图限制为 25