Django


1064 浏览 4 years, 9 months

7.1 模板渲染

版权声明: 转载请注明出处 http://www.codingsoho.com/

render

keyword

  • Context
  • RequestContext
  • render
  • get_template
  • HttpResponse
手动生成Html内容

最简单的渲染方法是直接生成html文件内容,然后通过HttpResonse函数渲染

from django.http import HttpResponse
def main_page(request):
    output = u'''
    <html>
    <head><title>%s</title></head>
    <body>
    <h1>%s</h1><p>%s</p>
    </body>
    </html>
    ''' % (
        u'Django Bookmarks',
        u'Welcome to Django Bookmarks',
        u'Where you can store and share bookmarks!'
        )
    return HttpResponse(output)
利用Template渲染
from django.template import Context, Template
from django.template.loader import get_template
def main_page(request):
    template = get_template('main_page.html')
    variables = Context({
        'user':request.user
    })
output = template.render(variables) 
return HttpResponse(output)

上面的代码已经告诉你如何载入一个模板文件,然后用 Context渲染它,最后返回这个处理好的HttpResponse对象给用户。

虽然已经优化了方案,使用 get_template() 方法代替繁杂的用代码来处理模板及其路径的工作, 但这仍然需要一定量的时间来敲出这些简化的代码。 这是一个普遍存在的重复苦力劳动。Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。

快捷方式render_to_response
from django.shortcuts import render_to_response
return render_to_response( 
    'main_page.html', 
    { 'user': request.user } 

上面的例子可进一步简化为

from django.shortcuts import render_to_response
return render_to_response( 
    'main_page.html', 
    RequestContext(request)) 

RequestContext vs Context

RequestContext adds a bunch of variables to your template context by default — things like the HttpRequest object or information about the currently logged-in user. Use RequestContext when you don’t want to have to specify the same set of variables in a series of templates.

Use a RequestContext object. This object is slightly different from normal Context objects. It automatically passes the user object to the template (along with several other variables). In order to do this, the RequestContext constructor takes the request object as its first parameter, and a dictionary of template variables as the second parameter.

项目中的例子

from django.template.context import RequestContext
from django.shortcuts import render_to_response
context = RequestContext(request, {
                'receivedContent' : responseMsg(request).replace('\r','').replace('\n',''),
                'SendContent' : sendContent.replace('\r','').replace('\n',''),
            })
return render_to_response("wechat.html", context)

Django1.8之后Template发生了改变,期望的输入参数为字典,而不再是一个context

https://docs.djangoproject.com/en/2.2/releases/1.8/

Rendering templates loaded by get_template() with a Context
The return type of get_template() has changed in Django 1.8: instead of a django.template.Template, it returns a Template instance whose exact type depends on which backend loaded it.

Both classes provide a render() method, however, the former takes a django.template.Context as an argument while the latter expects a dict. This change is enforced through a deprecation path for Django templates.

All this also applies to select_template().

上面的代码修改为

def main_page(request):
    template = get_template('main_page.html')
    output = template.render(variables) 
    variables = {
    'user':request.user,
    'title':u'Django Bookmarks',
    'h1':u'Welcome to Django Bookmarks',
    'p':u'Where you can store and share bookmarks!',
    }
    return HttpResponse(output)

模板文件main_page.html

<html>
<head><title>{{title}}</title></head>
<body>
<h1>{{h1}}</h1><p>{{p}}</p>
</body>
</html>
快捷方式render

render函数做了进一步的封装

from django.shortcuts import render
def main_page(request):
    variables = {
    'user':request.user,
    'title':u'Django Bookmarks',
    'h1':u'Welcome to Django Bookmarks',
    'p':u'Where you can store and share bookmarks!',
    }
    return render(request, "main_page.html", variables )