Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > Python网站web

浅谈django的render函数的参数问题

来源:中文源码网    浏览:474 次    日期:2024-04-27 17:01:43
【下载文档:  浅谈django的render函数的参数问题.txt 】


浅谈django的render函数的参数问题
hello.html 文件代码如下:
HelloWorld/templates/hello.html 文件代码:

{{ hello }}


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 来填充模板:
>>> from django.template import Context, Template
>>> t = Template('My name is {{ name }}.')
>>> c = Context({'name': 'nowamagic'})
>>> t.render(c)
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: 用于加载模板使用的模板引擎的名称。
以上这篇浅谈django的render函数的参数问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持中文源码网。

相关内容