From bee498f3a2f66210db39f0be244ec4fa888b6940 Mon Sep 17 00:00:00 2001 From: Luke Plant Date: Sat, 30 Jun 2012 18:54:38 +0100 Subject: Added 'format_html' utility for formatting HTML fragments safely --- docs/ref/utils.txt | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'docs/ref') diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index 549812296b..c74392df36 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -410,6 +410,45 @@ escaping HTML. Similar to ``escape()``, except that it doesn't operate on pre-escaped strings, so it will not double escape. +.. function:: format_html(format_string, *args, **kwargs) + + This is similar to `str.format`_, except that it is appropriate for + building up HTML fragments. All args and kwargs are passed through + :func:`conditional_escape` before being passed to ``str.format``. + + For the case of building up small HTML fragments, this function is to be + preferred over string interpolation using ``%`` or ``str.format`` directly, + because it applies escaping to all arguments - just like the Template system + applies escaping by default. + + So, instead of writing: + + .. code-block:: python + + mark_safe(u"%s %s %s" % (some_html, + escape(some_text), + escape(some_other_text), + )) + + you should instead use: + + .. code-block:: python + + format_html(u"%{0} {1} {2}", + mark_safe(some_html), some_text, some_other_text) + + This has the advantage that you don't need to apply :func:`escape` to each + argument and risk a bug and an XSS vulnerability if you forget one. + + Note that although this function uses ``str.format`` to do the + interpolation, some of the formatting options provided by `str.format`_ + (e.g. number formatting) will not work, since all arguments are passed + through :func:`conditional_escape` which (ultimately) calls + :func:`~django.utils.encoding.force_unicode` on the values. + + +.. _str.format: http://docs.python.org/library/stdtypes.html#str.format + ``django.utils.http`` ===================== -- cgit v1.3