Django模板继承和上下文翻译

6

我正在阅读《Django权威指南》第四章关于模板继承的部分。似乎我没有按照最优雅的方式进行操作,因为我需要复制一些代码来使上下文在调用子视图时出现。以下是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>

和一个子模板文件:

{% 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 %}

如果在调用子文件时不包含current_date行,那么变量应该出现的地方为空白。
3个回答

17

您可以通过使用上下文处理器将变量传递到每个模板中:

1. 将上下文处理器添加到您的配置文件中

首先,您需要将自定义上下文处理器添加到settings.py中:

# settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'myapp.context_processors.default', # add this line
    'django.core.context_processors.auth', 
)

由此可以推断出您需要创建一个名为context_processors.py的模块,并将其放置在您的应用程序文件夹中。您还可以看到它需要声明一个名为default的函数(因为这是我们在settings.py中包含的),但这是任意的。您可以选择任何您喜欢的函数名称。

2. 创建上下文处理器

# context_processors.py

from datetime import datetime
from django.conf import settings  # this is a good example of extra
                                  # context you might need across templates
def default(request):
    # you can declare any variable that you would like and pass 
    # them as a dictionary to be added to each template's context:
    return dict(
        example = "This is an example string.",
        current_date = datetime.now(),                
        MEDIA_URL = settings.MEDIA_URL, # just for the sake of example
    )

3. 在视图中添加额外的上下文

最后一步是使用RequestContext()处理额外的上下文并将其作为变量传递给模板。以下是需要对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))

3
因此,您可以使用django.views.generic.simple.direct_to_template而不是render_to_response。它在内部使用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'
    })

或者你甚至可以直接在urls.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'},        
    }),

2

对于django v1.8+,在上下文处理器中返回的变量可以被访问。

1. 在settings.py里的TEMPLATES列表中添加上下文处理器

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

           ],
       },
   },
]

2. 创建新文件用于上下文处理器并定义上下文方法

context_processor_file.py

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

3.现在你可以在任何模板中获取var_for_template

例如,在base.html中添加以下行:

<h1>{{ var_for_template }}</h1>  

这将呈现为:

<h1>hi, this is a variable from context processor</h1>

如果要将模板更新到Django 1.8+,请遵循此Django文档


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