django模板继承和上下文

django模板继承和上下文,django,django-templates,Django,Django Templates,我正在阅读django的权威指南,我在第4章关于模板继承。似乎我没有尽可能地做一些优雅的事情,因为我必须复制一些代码,以便在调用子视图时显示上下文。以下是views.py中的代码: def homepage(request): current_date = datetime.datetime.now() current_section = 'Temporary Home Page' return render_to_response("base.html", locals

我正在阅读django的权威指南,我在第4章关于模板继承。似乎我没有尽可能地做一些优雅的事情,因为我必须复制一些代码,以便在调用子视图时显示上下文。以下是views.py中的代码:

def homepage(request):
    current_date = datetime.datetime.now()
    current_section = 'Temporary Home Page'
    return render_to_response("base.html", locals())
def contact(request):
    current_date = datetime.datetime.now()
    current_section = 'Contact page'
    return render_to_response("contact.html", locals())
在每个函数中包含当前的_日期行似乎是多余的

以下是主页调用的基本html文件:

<html lang= "en">
<head>
    <title>{% block title %}Home Page{% endblock %}</title>
</head>
<body>
    <h1>The Site</h1>
    {% block content %}
        <p> The Current section is {{ current_section }}.</p>
    {% endblock %}

    {% block footer %}
    <p>The current time is {{ current_date }}</p>
    {% endblock %}
</body>
</html>

{%block title%}主页{%endblock%}
场地
{%block content%}
当前节是{Current_section}}

{%endblock%} {%block footer%} 当前时间为{current_date}}

{%endblock%}
和子模板文件:

{% extends "base.html" %}

{% block title %}Contact{% endblock %}

{% block content %}
<p>Contact information goes here...</p>
    <p>You are in the section {{ current_section }}</p>
{% endblock %}
{%extends“base.html”%}
{%block title%}联系人{%endblock%}
{%block content%}
联系信息在这里

您在{current_section}节中

{%endblock%}

如果调用子文件时未包含当前日期行,则该变量应显示的位置为空。

您可以使用以下命令将变量传递给每个模板:

1.将上下文处理器添加到设置文件 首先,您需要将自定义上下文处理器添加到
设置中。py

# settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'myapp.context_processors.default', # add this line
    'django.core.context_processors.auth', 
)
从中可以推断出,您需要创建一个名为
context\u processors.py
的模块,并将其放在应用程序文件夹中。您可以进一步看到,它需要声明一个名为
default
(正如我们在
settings.py
中所包含的那样)的函数,但这是任意的。您可以选择您喜欢的函数名

2.创建上下文处理器 3.向视图中添加额外的上下文 最后一步是使用处理附加上下文,并将其作为变量传递给模板。下面是对
views.py
文件进行修改的一个非常简单的示例:

# old views.py
def homepage(request):
    current_date = datetime.datetime.now()
    current_section = 'Temporary Home Page'
    return render_to_response("base.html", locals())

def contact(request):
    current_date = datetime.datetime.now()
    current_section = 'Contact page'
    return render_to_response("contact.html", locals())


# new views.py
from django.template import RequestContext

def homepage(request):
    current_section = 'Temporary Home Page'
    return render_to_response("base.html", locals(),
                              context_instance=RequestContext(request))

def contact(request):
    current_section = 'Contact page'
    return render_to_response("contact.html", locals(),
                              context_instance=RequestContext(request))

因此,您可以使用django.views、generic.simple.direct_to_模板,而不是render_to_响应。它在内部使用RequestContext

from django.views,generic.simple import direct_to_template

def homepage(request):
    return direct_to_template(request,"base.html",{
        'current_section':'Temporary Home Page'
    })

def contact(request):
    return direct_to_template(request,"contact.html",{
        'current_section':'Contact Page'
    })
或者您甚至可以直接在url.py中指定它,例如

urlpatterns = patterns('django.views.generic.simple',
    (r'^/home/$','direct_to_template',{
        'template':'base.html'
        'extra_context':{'current_section':'Temporary Home Page'},        
    }),
    (r'^/contact/$','direct_to_template',{
        'template':'contact.html'
        'extra_context':{'current_section':'Contact page'},        
    }),

对于django v1.8+,可以访问内部返回的变量

1.将上下文处理器添加到
设置.py中的
模板
列表中 2.为上下文处理器创建新文件并为上下文定义方法
context\u processor\u file.py

3.现在,您可以在任何模板中获得
var\u for\u模板
例如,将这一行添加到:
base.html

{{var\u for_template}
这将导致:

hi,这是来自上下文处理器的变量
urlpatterns = patterns('django.views.generic.simple',
    (r'^/home/$','direct_to_template',{
        'template':'base.html'
        'extra_context':{'current_section':'Temporary Home Page'},        
    }),
    (r'^/contact/$','direct_to_template',{
        'template':'contact.html'
        'extra_context':{'current_section':'Contact page'},        
    }),
TEMPLATES = [
   {
       'BACKEND': 'django.template.backends.django.DjangoTemplates',
       'DIRS': [],
       'APP_DIRS': True,
       'OPTIONS': {
           'context_processors': [
               'django.template.context_processors.debug',
               'django.template.context_processors.request',
               'django.contrib.auth.context_processors.auth',
               'django.contrib.messages.context_processors.messages',

               'your_app.context_processor_file.func_name',  # add this line

           ],
       },
   },
]
def func_name(request):
  test_var = "hi, this is a variable from context processor"
  return {
    "var_for_template" : test_var,
  }
<h1>{{ var_for_template }}</h1>