Django模板中的request.path是什么意思?

8
我试了以下内容:

我尝试了这样的方式:

{% if request.path == 'contact' %}
    <p>You are in Contact</p>
{% endif %}

{% if request.path == 'shop' %}
    <p>You are in Shop</p>
{% endif %}

为什么这样不起作用?

你的TEMPLATE_CONTEXT_PROCESSORS设置中包含了什么? - Brandon Taylor
@Brandon 我的settings.py中没有这个配置。我使用的是django 1.4.5。我想我使用的是默认设置。 - Emanuel
2
尝试输出 {{ request.path }} - sneawo
4个回答

16

默认情况下,Django的模板处理器为

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"
)

(请参见文档

在模板中使用request,需要添加django.core.context_processors.requestsettings.py文件的列表中。如果你的设置中没有该变量,则设置它。


1
从Django 1.10+开始,请使用“django.template.context_processors.request”。 - Mojtaba Arvin

7

试试这个:

{% if 'contact' in request.path %}

4

尝试:

{% if request.path == '/contact/' %}
    <p>You are in Contact</p>
{% elif request.path == '/shop/' %}
    <p>You are in Shop</p>
{% endif %}

request.path会给你整个路径,所以如果路径看起来像这样/something/someting/contact/,那就是它。 - Henrik Andersson
没错。你必须检查整个路径,我只是根据提供的内容举了个例子 :) - Brandon Taylor
尝试检查{% if 'contact/' in reuqest.path %}。这样您就不需要检查完整路径。 - danbruegge

0

1.8版本之前 settings.py文件

TEMPLATE_CONTEXT_PROCESSORS = (
    'other.required.processors.names',
    'django.core.context_processors.request',
)

views.py(使用className.as_view)

from django.template import *

class className(TemplateView):
    template_name = "name.html"

views.py(正常使用)

from django.shortcuts import render_to_response

def name(request):
    return render_to_response('name.html'{},context_instance=RequestContext(request))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接