0

我有一个这样的问题,我用谷歌搜索了很多,阅读了decoratorsand middleware,但我没有明白如何更好地解决我的问题。

我有基本模板base.html和模板template1.htmltemplate2.html它们是base.html.

base.html有一些通用块,在 和 中是必需template1.htmltemplate2.html。这个块是动态数据,所以我必须在每个视图中获取这个块的数据,然后渲染模板。

例如我有 2 views

@render_to("template1.html")
def fun_1(request):
data = getGeneralData()
#...getting other data
return {
        "data" : data,
        "other" : other_data,
}

@render_to("template2.html")
def fun_2(request):
data = getGeneralData()
#...getting other data
return {
        "data" : data,
        "other2" : other_data2,
}

所以一般来说,我需要这个getGeneralData在我的所有视图中都需要这个,我是否可以在我的每个视图views中调用getGeneralData()函数,或者我可以制作任何函数,general_data在任何视图获取自己的数据之前获取并将其渲染到模板?

您能否提供一个代码示例或给我一个很好的链接如何做得更好?

4

2 回答 2

1

将建议您编写自己的上下文处理器并从那里返回所需的上下文数据。

例子 :

custom_context_processor.py

def ctx_getGeneralData(request):
    ctx = {}
    ctx['data'] = getGeneralData()
    return ctx

在设置文件中,更新TEMPLATE_CONTEXT_PROCESSORS'custom_context_processor.ctx_getGeneralData'

于 2012-11-08T13:13:38.873 回答
1

您是否考虑过使用 Django 的基于类的视图?它们最初有点难以使用,但它们使这样的事情变得非常简单。以下是我如何使用基于类的视图重写基于函数的视图:

# TemplateView is a generic class based view that simply
# renders a template.
from django.views.generic import TemplateView


# Let's start by defining a mixin that we can mix into any view that
# needs the result of getGeneralData() in its template context.


class GeneralContextDataMixin(object):
    """
    Adds the result of calling getGeneralData() to the context of whichever
    view it is mixed into.
    """

    get_context_data(self, *args, **kwargs):
        """
        Django calls get_context_data() on all CBVs that render templates.
        It returns a dictionary containing the data you want to add to
        your template context.
        """
        context = super(GeneralContextDataMixin, self).get_context_data(*args, **kwargs)
        context['data'] = getGeneralData()
        return context


# Now we can inherit from this mixin wherever we need the results of
# getGeneralData(). Note the order of inheritance; it's important.


class View1(GeneralContextDataMixin, TemplateView):
    template_name = 'template1.html'


class View2(GeneralContextDataMixin, TemplateView):
    template_name = 'template2.html'

当然,您也可以像 Rohan 所说的那样编写自己的上下文处理器。事实上,如果您想将此数据添加到所有视图中,我建议您这样做。

无论您最终做什么,我都会敦促您研究基于类的视图。它们使许多重复性任务变得非常容易。

进一步阅读:

于 2012-11-08T14:28:17.953 回答