【问题标题】:django: call function from views in templatedjango:从模板中的视图调用函数
【发布时间】:2012-11-11 09:56:56
【问题描述】:

我在views.py 中有一个函数,例如这样的:

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

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

【问题讨论】:

    标签: django function templates views


    【解决方案1】:

    如果你想在所有模板上显示这个变量,那么你需要实现一个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 }}

    【讨论】:

      【解决方案2】:

      您需要创建一个模板标签,对于您的情况,您可能需要查看inclusion tag

      【讨论】:

        猜你喜欢
        • 2014-08-18
        • 2013-07-10
        • 2011-03-11
        • 2018-03-07
        • 1970-01-01
        • 2019-01-30
        • 2010-10-22
        • 2011-01-03
        • 1970-01-01
        相关资源
        最近更新 更多