三剑客之render

def render(request, template_name, context=None, content_type=None, status=None, using=None):
    """
    Return a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, status)

结合一个给定的模板和一个给定的上下文字典, 并返回一个渲染的Httpresponse对象

参数:

request: 用于生成响应的请求对象
template_name: 要使用的模板的完整名称, 可选的参数
context: 添加到模板上下文的一个字典. 默认是一个空字典. 如果字典中的某个值是可调用的, 视图将在渲染模板之前调用它.
content_type:  生成的文档要使用的MIME类型. 默认为DEFAULT_CONTENT_TYPE设置的值. 默认为"text/html"
status: 响应的状态码. 默认为200
useing: 用于加载模板的模板引擎的名称

用法:

from django.shortcuts import render

def login_view(request):
    return render(request, 'login.html', {'foo': 'bar'})

在源码中会走loader.render_to_sering

def render_to_string(template_name, context=None, request=None, using=None):
    """
    Load a template and render it with a context. Return a string.

    template_name may be a string or a list of strings.
    """
    if isinstance(template_name, (list, tuple)):
        template = select_template(template_name, using=using)
    else:
        template = get_template(template_name, using=using)
    return template.render(context, request)

就是判断模板名是否是列表或元组, 一般我们都是使用一个文件名

所以上方用法就相当于:

from django.shortcuts import HttpResponse
from django.template import loader

def login_view(request):
    t = loader.get_template('login.html')
    c = {'foo': 'bar'}
    return HttpResponse(t.render(c, request))

猜你喜欢

转载自www.cnblogs.com/yuyafeng/p/12449910.html
今日推荐