From e889c4a2b8b4258d788a6e9466b4c0e693918acc Mon Sep 17 00:00:00 2001
From: Gisle Aas <gisle@aas.no>
Date: Mon, 22 Feb 2010 08:10:00 -0500
Subject: [PATCH] Faster escapejs #11778
---
django/template/defaultfilters.py | 44 ++++++++++++++++++++----------------
1 files changed, 24 insertions(+), 20 deletions(-)
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index e6492dc..950cc16 100644
a
|
b
|
def capfirst(value):
|
68 | 68 | capfirst.is_safe=True |
69 | 69 | capfirst = stringfilter(capfirst) |
70 | 70 | |
71 | | _base_js_escapes = ( |
72 | | ('\\', r'\x5C'), |
73 | | ('\'', r'\x27'), |
74 | | ('"', r'\x22'), |
75 | | ('>', r'\x3E'), |
76 | | ('<', r'\x3C'), |
77 | | ('&', r'\x26'), |
78 | | ('=', r'\x3D'), |
79 | | ('-', r'\x2D'), |
80 | | (';', r'\x3B'), |
81 | | (u'\u2028', r'\u2028'), |
82 | | (u'\u2029', r'\u2029') |
83 | | ) |
84 | | |
85 | | # Escape every ASCII character with a value less than 32. |
86 | | _js_escapes = (_base_js_escapes + |
87 | | tuple([('%c' % z, '\\x%02X' % z) for z in range(32)])) |
| 71 | _js_escapes_dict = { |
| 72 | '\\': r'\x5C', |
| 73 | '\'': r'\x27', |
| 74 | '"': r'\x22', |
| 75 | '>': r'\x3E', |
| 76 | '<': r'\x3C', |
| 77 | '&': r'\x26', |
| 78 | '=': r'\x3D', |
| 79 | '-': r'\x2D', |
| 80 | ';': r'\x3B', |
| 81 | u'\u2028': r'\u2028', |
| 82 | u'\u2029': r'\u2029', |
| 83 | } |
| 84 | |
| 85 | # also escape every ASCII character with a value less than 32. |
| 86 | for z in range(32): |
| 87 | _js_escapes_dict[chr(z)] = '\\x%02X' % z |
| 88 | |
| 89 | # construct a Regex object matching the keys in _js_escapes_dict |
| 90 | _js_escapes_re = u''.join(sorted(_js_escapes_dict.keys())) |
| 91 | _js_escapes_re = re.sub(r'[\\\\\-\]]', r'\\\g<0>', _js_escapes_re) # escape \-] |
| 92 | _js_escapes_re = '[' + _js_escapes_re + ']' |
| 93 | _js_escapes_re = re.compile(_js_escapes_re) |
88 | 94 | |
89 | 95 | def escapejs(value): |
90 | 96 | """Hex encodes characters for use in JavaScript strings.""" |
91 | | for bad, good in _js_escapes: |
92 | | value = value.replace(bad, good) |
93 | | return value |
| 97 | return _js_escapes_re.sub(lambda m: _js_escapes_dict[m.group(0)], value) |
94 | 98 | escapejs = stringfilter(escapejs) |
95 | 99 | |
96 | 100 | def fix_ampersands(value): |