django模板中的request.path

时间:2013-03-15 15:38:32

标签: django

我尝试这样的事情:

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

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

为什么不起作用?

4 个答案:

答案 0 :(得分:15)

默认情况下,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"
)

(见documentation

您需要django.core.context_processors.request在模板中使用request,因此请将其添加到 settings.py 中的该列表中。如果你没有那个变量那么就设置它。

答案 1 :(得分:2)

尝试:

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

答案 2 :(得分: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))

答案 3 :(得分:0)

尝试一下:

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