您的位置:首页 > 编程语言 > Go语言

关于django的render函数的参数问题

2017-06-28 14:46 323 查看
hello.html 文件代码如下:


HelloWorld/templates/hello.html 文件代码:

<h1>{{
hello }}</h1>


HelloWorld/HelloWorld/view.py 文件代码:

# -*- coding: utf-8 -*-

#from django.http import HttpResponse
from django.shortcuts import render

def hello(request):
context          = {}
context['hello'] = 'Hello World!'
return render(request, 'hello.html', context)


ontext 字典中元素的键值 "hello" 对应了模板中的变量 "{{ hello }}"。

一旦你创建一个 Template 对象,你可以用 context 来传递数据给它。 一个context 是一系列变量和它们值的集合。

context 在 Django 里表现为 Context 类,在 django.template 模块里。它的构造函数带有一个可选的参数: 一个字典映射变量和它们的值。 调用 Template 对象 的 render() 方法并传递 context 来填充模板:

1
>>> 
from
 
django.template 
import
 
Context,
Template
2
>>>
t 
=
 
Template(
'My
name is {{ name }}.'
)
3
>>>
c 
=
 
Context({
'name'
'nowamagic'
})
4
>>>
t.render(c)
5
u
'My
name is nowamagic.'
我们必须指出的一点是,t.render(c) 返回的值是一个 Unicode 对象,不是普通的 Python 字符串。 你可以通过字符串前的 u 来区分。 在框架中,Django 会一直使用 Unicode 对象而不是普通的字符串。 如果你明白这样做给你带来了多大便利的话,尽可能地感激 Django 在幕后有条不紊地为你所做这这么多工作吧。 如果不明白你从中获益了什么,别担心。你只需要知道 Django 对 Unicode 的支持,将让你的应用程序轻松地处理各式各样的字符集,而不仅仅是基本的A-Z英文字符。
from django.shortcuts import render

help文档中描述如下:

render(request, template_name, context=None, content_type=None, status=None, using=None)

Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.

此方法的作用---结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

通俗的讲就是把context的内容, 加载进templates中定义的文件, 并通过浏览器渲染呈现.

参数讲解:

request: 是一个固定参数, 没什么好讲的。

template_name: templates 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.html’

context: 要传入文件中用于渲染呈现的数据, 默认是字典格式

content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE
设置的值。

status: http的响应代码,默认是200.

using: 用于加载模板使用的模板引擎的名称。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: