栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

关于Django的render函数的参数和模板语言转义处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于Django的render函数的参数和模板语言转义处理

1. render函数的参数

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

{{ hello }}

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

from django.shortcuts import render

 
def hello(request):

    context = {'hello': 'Hello World!'}

    return render(request, 'hello.html', context)

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

view.py下导入库:

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 中定义的文件, 要注意路径名. 比如'templatespollsindex.html', 参数就要写‘pollsindex.html’。

settings.py下要配置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

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

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

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

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

2. Django模板语言转义处理

如果hello.html模板中的"{{ hello }}"内容含html的话,django的模板系统默认会对输出进行转义(把内容转义成字符串),比如把

转义成了<p> ,然后再显示出来的时候就如实地显示为

。如下所示:

要解决这个问题只要把默认的自动转义关闭就好了。比如原本我们的模板代码是这样的:{{post.content}}

有两种方式可以解决:

方法一,关闭autoescape:

{% autoescape off %}

{{post.content}}

{% endautoescape %}

方法二,使用| safe过滤器: 

{{post.content | safe}}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号