Ticket #7261: html.diff

File html.diff, 2.4 KB (added by Jeff Balogh, 15 years ago)

implement html on SafeData for template engine interop

  • django/utils/html.py

    diff --git a/django/utils/html.py b/django/utils/html.py
    index 951b3f2..8d8d673 100644
    a b def conditional_escape(html):  
    3838    """
    3939    Similar to escape(), except that it doesn't operate on pre-escaped strings.
    4040    """
    41     if isinstance(html, SafeData):
    42         return html
     41    if hasattr(html, '__html__'):
     42        return html.__html__()
    4343    else:
    4444        return escape(html)
    4545
  • django/utils/safestring.py

    diff --git a/django/utils/safestring.py b/django/utils/safestring.py
    index 2e31c23..6f7a22a 100644
    a b class EscapeUnicode(unicode, EscapeData):  
    2222    pass
    2323
    2424class SafeData(object):
    25     pass
     25
     26    def __html__(self):
     27        """
     28        Returns the html representation of a string.
     29
     30        Allows interoperability with other template engines.
     31        """
     32        return self
    2633
    2734class SafeString(str, SafeData):
    2835    """
  • tests/regressiontests/utils/tests.py

    diff --git a/tests/regressiontests/utils/tests.py b/tests/regressiontests/utils/tests.py
    index 4ad4e63..01b712d 100644
    a b Tests for django.utils.  
    44
    55from unittest import TestCase
    66
    7 from django.utils import html, checksums, text
     7from django.utils import html, checksums, text, safestring
    88from django.utils.functional import SimpleLazyObject
    99
    1010import timesince
    class TestUtilsHtml(TestCase):  
    144144        for value, output in items:
    145145            self.check_output(f, value, output)
    146146
     147    def test_conditional_escape(self):
     148        s = '<h1>interop</h1>'
     149        self.assertEqual(html.conditional_escape(s),
     150                         '&lt;h1&gt;interop&lt;/h1&gt;')
     151        self.assertEqual(html.conditional_escape(safestring.mark_safe(s)), s)
     152
    147153class TestUtilsChecksums(TestCase):
    148154
    149155    def check_output(self, function, value, output=None):
    class TestUtilsText(TestCase):  
    262268        self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>',
    263269            text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None))
    264270
     271class TestSafeData(TestCase):
     272
     273    def test_html(self):
     274        s = '<h1>interop</h1>'
     275        self.assertEqual(s, safestring.mark_safe(s).__html__())
     276
    265277if __name__ == "__main__":
    266278    import doctest
    267279    doctest.testmod()
Back to Top