diff --git a/common/djangoapps/util/markup.py b/common/djangoapps/util/markup.py new file mode 100644 index 0000000000..304533de32 --- /dev/null +++ b/common/djangoapps/util/markup.py @@ -0,0 +1,51 @@ +""" +Utilities for use in Mako markup. +""" + +from django.utils.translation import ugettext as django_ugettext +from django.utils.translation import ungettext as django_ungettext +import markupsafe + + +# So that we can use escape() imported from here. +escape = markupsafe.escape # pylint: disable=invalid-name + + +def ugettext(text): + """Translate a string, and escape it as plain text. + + Use like this in Mako:: + + <% from util.markup import ugettext as _ %> +
${_("Hello, world!")}
+ + Or with formatting:: + + <% from util.markup import HTML, ugettext as _ %> + ${_("Write & send {start}email{end}").format( + start=HTML(""), + end=HTML(""), + )} + + """ + return markupsafe.escape(django_ugettext(text)) + + +def ungettext(text1, text2, num): + """Translate a number-sensitive string, and escape it as plain text.""" + return markupsafe.escape(django_ungettext(text1, text2, num)) + + +def HTML(html): # pylint: disable=invalid-name + """Mark a string as already HTML, so that it won't be escaped before output. + + Use this when formatting HTML into other strings:: + + <% from util.markup import HTML, ugettext as _ %> + ${_("Write & send {start}email{end}").format( + start=HTML(""), + end=HTML(""), + )} + + """ + return markupsafe.Markup(html) diff --git a/common/djangoapps/util/tests/test_markup.py b/common/djangoapps/util/tests/test_markup.py new file mode 100644 index 0000000000..d700df57f8 --- /dev/null +++ b/common/djangoapps/util/tests/test_markup.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" +Tests for util.markup +""" + +import unittest + +import ddt + +from edxmako.template import Template +from util.markup import escape, HTML, ugettext as _, ungettext + + +@ddt.ddt +class FormatHtmlTest(unittest.TestCase): + """Test that we can format plain strings and HTML into them properly.""" + + @ddt.data( + (u"hello", u"hello"), + (u"