2010-09-15 129 views
5

我正在閱讀django權威指南,並在第4章中介紹了模板繼承。看起來,我沒有做盡可能優雅的事情,因爲我不得不復制一些代碼,以便在調用子視圖時顯示上下文。這裏是views.py中的代碼:django模板繼承和上下文

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

在每個函數中都必須包含current_date行似乎是多餘的。

這裏是主頁電話基本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線該變量應該顯示爲空白。

回答

16

您可以通過使用一個Context Processor變量傳遞給每一個模板:

1.添加背景處理器將您的設置文件

首先,你需要添加自定義背景處理器到您的settings.py

# settings.py 

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

從這個你可以得到你,你將需要創建一個名爲context_processors.py模塊,並將其放在您的應用程序的內部FOL DER。您可以進一步看到它需要聲明一個名爲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'},   
    }), 
0

Django的V1.8 +內context processor返回變量直接指定可以訪問。

1.背景處理器添加到您的TEMPLATES列表裏面settings.py

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+遵循this django doc