当前位置: 移动技术网 > IT编程>脚本编程>Python > 浅谈django的render函数的参数问题

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

2018年11月08日  | 移动技术网IT编程  | 我要评论

连锁店加盟网,广州公车查询,丹彤健身俱乐部

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 来填充模板:

>>> 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\', 参数就要写‘polls\'

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

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

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

using: 用于加载模板使用的模板引擎的名称。

以上这篇浅谈django的render函数的参数问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网