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

1. render函数的参数

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

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

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 中定义的文件, 要注意路径名. 比如'templates\polls\index.html', 参数就要写‘polls\index.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>转义成了&lt;p&gt; ,然后再显示出来的时候就如实地显示为<p>。如下所示:

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

有两种方式可以解决:

方法一,关闭autoescape:

{% autoescape off %}

{{post.content}}

{% endautoescape %}

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

{{post.content | safe}}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值