脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 浅谈django的render函数的参数问题

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

2021-04-08 00:26慢慢的踏实走 Python

今天小编就为大家分享一篇浅谈django的render函数的参数问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

hello.html 文件代码如下:

?
1
2
HelloWorld/templates/hello.html 文件代码:
<h1>{{ hello }}</h1>

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

?
1
2
3
4
5
6
7
8
9
# -*- 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
2
3
4
5
6
7
8
9
>>> 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函数的参数问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u013176681/article/details/73844330

延伸 · 阅读

精彩推荐