django:从模板中的视图调用函数

时间:2012-11-11 09:56:56

标签: django function templates views

我在views.py中有一个功能,例如:

def get_base_content():
    footer = SiteContent.objects.get(pk=1)
    return {
        "footer" : footer,
}

我如何在template中调用此函数并在其中使用footer变量?

2 个答案:

答案 0 :(得分:2)

如果您希望在所有模板上显示此变量,则需要实现template context processor

您只需对代码进行最少的更改:

def get_base_content(request):
    footer = SiteContent.objects.get(pk=1)
    return {"footer" : footer}

现在,将其添加到单独的文件中,将其命名为custom_context.py。在settings.py中将其添加到TEMPLATE_CONTEXT_PROCESSORS设置:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "myapp.custom_context.get_base_content", # don't forget the comma!
)

现在,在您的视图代码中,您只需确保使用RequestContext。最简单的方法是使用render shortcut

from django.shortcuts import render

def myview(request):
   return render(request,'hello.html',{'foo': 'bar'})

hello.html中,您将拥有{{ foo }}{{ footer }}

答案 1 :(得分:1)

您需要创建模板标记,根据您的情况,您可能需要查看inclusion tag