1.RequestContext和Context处理器
views.py
from django.http import HttpResponse from django.template import loader, Context def view_1(request): t = loader.get_template(‘app.html‘) c = Context({ ‘app‘: ‘My app‘, ‘user‘: ‘a‘, ‘ip_address‘: ‘b‘, ‘message‘: ‘I am view 1.‘ }) html = t.render(c) return HttpResponse(html)
urls.py
from books import views (r‘^context/$‘, views.view_1)
app.html
{{app}} {{user}} {{ip_address}} {{message}}
访问http://192.168.1.22/context/,运行结果:
My app a b I am view 1.
2.三种方式实现相同的输出
views.py
from django.http import HttpResponse #def current_datetime(request): # now = datetime.datetime.now() # html = "<html><body>It is now %s.</body></html>" % now # return HttpResponse(html) #def current_datetime(request): # now = datetime.datetime.now() # t = get_template(‘current_datetime.html‘) # html = t.render(Context({‘current_date‘:now})) #return HttpResponse(html) def current_datetime(request): now = datetime.datetime.now() return render_to_response(‘dataapp/current_datetime.html‘,{‘current_date‘:now})
urls.py
from books import views (r‘^time/$‘,current_datetime),
current_datetime.html
{% extends "base.html" %} {% block title %} The current time {% endblock %} {% block content %} <p> It is now{{ current_date }}.</p> {% endblock %}
访问结果:
原文地址:http://dragonball.blog.51cto.com/1459915/1430366