Tim*_* S. 5 python django django-templates
与这篇文章相关,我想从单个 Django 视图中填充多个 HTML 页面。这与我刚才提到的链接之间的区别是,我不希望它以编程方式为基础。我的模板上有链接,例如“报告”和其他公司特定的类别。如果用户单击“报告”链接,我想将他们带到一个新页面,该页面将向他们显示报告。这些数据都是相互关联的,所以我最初假设我会/应该对所有这些数据使用相同的视图。不过,当我开始写这篇文章时,我开始怀疑我是否应该为所有页面使用单独的视图。总共不应超过 3-4 页,具体取决于我想如何划分类别。
So TL;DR: Should I use separate views for each HTML page in my template, or should/could I use a single view to populate all of the various pages on the site, even if most of the data comes from the same sources?
使用基于类的视图的一种可能解决方案是创建一个基本视图类,该类将收集公共上下文数据,然后根据需要为特定数据和模板扩展它。实际上基类不必是 的扩展View,ContextMixin扩展就足够了
基类应如下所示:
class BaseContextMixin(ContextMixin):
def get_context_data(self, **kwargs):
context_data = super(BaseContextMixin, self).get_context_data(**kwargs)
common_data_1 = ...
context_data["common_key_1"] = common_data_1
common_data_2 = ...
context_data["common_key_2"] = common_data_2
...
return context_data
Run Code Online (Sandbox Code Playgroud)
然后可以按如下方式实施这些意见:
class MyFirstView(TemplateView, BaseContextMixin):
template_name = "mir/my_first_template.html"
def get_context_data(self, **kwargs):
context_data = super(MyFirstView, self).get_context_data(**kwargs)
context_data["my_special_key"] = my_special_data
return context_data
class MySecondView(TemplateView, BaseContextMixin):
template_name = "mir/my_second_template.html"
def get_context_data(self, **kwargs):
context_data = super(MySecondView, self).get_context_data(**kwargs)
context_data["my_special_key_2"] = my_special_data_2
return context_data
Run Code Online (Sandbox Code Playgroud)
这样可以避免冗余代码,同时可以保持结构简单
| 归档时间: |
|
| 查看次数: |
2599 次 |
| 最近记录: |