【问题标题】:How do I display the results of a python function in Django's base.html file?如何在 Django 的 base.html 文件中显示 python 函数的结果?
【发布时间】:2013-05-27 15:08:37
【问题描述】:

我的views.py 中当前定义了以下函数:

def display_path_url(request):
    return HttpResponse("Current Path: %s" % request.path)

假设我正在访问127.0.0.1:8000/product_list,我将打印product_list/

我需要在 Django 中的每个渲染页面上打印此信息。这就是为什么我希望在base.html 中调用这个函数。

我该怎么做?

感谢您的帮助。

PS:我试图从其他 Stackoverlow 帖子中找到答案,但找不到任何解决方案。我希望这个问题不会与其他问题重复。

【问题讨论】:

    标签: python django django-templates base


    【解决方案1】:

    request 变量在 Django 模板中可用。您可以从任何地方访问它。不仅base.html。像这样——

    {{ request.path }}
    

    Read more.

    【讨论】:

      【解决方案2】:

      正如 karthikr 和 Bibhas 已经提到的,您无需做太多工作即可访问模板中的当前 request(假设模板是使用 RequestContext 呈现的,参见 https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext)。

      作为一个更一般的答案,如果您想从任何模板中使用函数,那么最好的方法是编写自定义过滤器或模板标签,如下所述:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 2019-10-22
        • 2016-01-03
        • 1970-01-01
        • 2015-01-13
        • 1970-01-01
        • 2017-09-30
        相关资源
        最近更新 更多