Added 'format_html' utility for formatting HTML fragments safely

This commit is contained in:
Luke Plant 2012-06-30 18:54:38 +01:00
parent f33e150369
commit bee498f3a2
3 changed files with 81 additions and 0 deletions

View file

@ -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 <b>%s</b> %s" % (some_html,
escape(some_text),
escape(some_other_text),
))
you should instead use:
.. code-block:: python
format_html(u"%{0} <b>{1}</b> {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``
=====================