7

我尝试这样的事情:

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

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

为什么那行不通?

4

4 回答 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"
)

(见文档

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

于 2013-03-15T15:58:31.303 回答
5

尝试这个:

{% if 'contact' in request.path %}
于 2019-05-26T07:20:24.823 回答
2

尝试:

{% if request.path == '/contact/' %}
    <p>You are in Contact</p>
{% elif request.path == '/shop/' %}
    <p>You are in Shop</p>
{% endif %}
于 2013-03-15T15:48:41.287 回答
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))
于 2015-12-16T11:57:30.960 回答