Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1181007
  • 博文数量: 272
  • 博客积分: 3899
  • 博客等级: 中校
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-15 14:53
文章分类

全部博文(272)

文章存档

2012年(272)

分类: 系统运维

2012-06-27 11:04:38

最近在review一个基于djangopython项目的时候,发现变量都auto escape过了。

因为以前django的项目,我们都要求模板里的变量做escape,要这样写:

{{ var|escape }}

比如在 django 0.9.6 里,就都要这样写。

遇到这个项目,我觉得很奇怪,去查了下django的文档,发现在 Django 1.0里,已经开始默认对所有变量做 escape

前提是使用django提供的模板系统。

参考以下示例:

# views.py

from django.shortcuts import render_to_response

def say_hello(request):
    name = request.GET.get('name', 'world')
    return render_to_response('hello.html', {'name': name})

# hello.html

Hello, {{ name }}!

在实际输出时会变成

Hello, <i>Jacob</i>!

django目前只对5个字符做了escape

< is converted to <

> is converted to >

' (single quote) is converted to '

" (double quote) is converted to "

& is converted to &

如果要关掉,可以使用

This will be escaped: {{ data }}
This will not be escaped: {{ data|safe }}

或者
{% autoescape off %}
    Hello {{ name }}
{% endautoescape %}


从手动到自动,是非常重要的,这是我们的最佳实践。

在一年前,我写过这篇文章:
Google Auto-Escape on Template 项目

今天,看到django能实现这种功能,是让人非常振奋的一件事情。

阅读(1421) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~