Ticket #10107: safestring.diff

File safestring.diff, 2.0 KB (added by matehat, 16 years ago)
  • django/utils/safestring.py

     
    44that the producer of the string has already turned characters that should not
    55be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
    66"""
    7 from django.utils.functional import curry, Promise
     7from django.utils.functional import curry, wraps, Promise
    88
    99class EscapeData(object):
    1010    pass
     
    8686
    8787    encode = curry(_proxy_method, method = unicode.encode)
    8888
    89 def mark_safe(s):
     89def _safety_decorator(safety_marker, func):
     90  @wraps(func)
     91  def wrapped(*args, **kwargs):
     92    return safety_marker(func(*args, **kwargs))
     93  return wrapped
     94
     95
     96def mark_safe(s=None):
    9097    """
    9198    Explicitly mark a string as safe for (HTML) output purposes. The returned
    9299    object can be used everywhere a string or unicode object is appropriate.
    93100
    94101    Can be called multiple times on a single string.
    95102    """
     103    if s is None: # Used like: @mark_safe()
     104        return curry(_safety_decorator, mark_safe)
     105    if callable(s): # Used like: @mark_safe
     106        return _safety_decorator(mark_safe, s)
    96107    if isinstance(s, SafeData):
    97108        return s
    98109    if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str):
     
    101112        return SafeUnicode(s)
    102113    return SafeString(str(s))
    103114
    104 def mark_for_escaping(s):
     115def mark_for_escaping(s=None):
    105116    """
    106117    Explicitly mark a string as requiring HTML escaping upon output. Has no
    107118    effect on SafeData subclasses.
     
    109120    Can be called multiple times on a single string (the resulting escaping is
    110121    only applied once).
    111122    """
     123   
     124    if s is None:
     125        return curry(_safety_decorator, mark_for_escaping)
     126    if callable(s):
     127        return _safety_decorator(mark_for_escaping, s)
    112128    if isinstance(s, (SafeData, EscapeData)):
    113129        return s
    114130    if isinstance(s, str) or (isinstance(s, Promise) and s._delegate_str):
Back to Top