utils.html.format_html()

format_html(format_string, *args, **kwargs) [source]

This is similar to str.format(), except that it is appropriate for building up HTML fragments. All args and kwargs are passed through 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:

mark_safe("%s <b>%s</b> %s" % (
    some_html,
    escape(some_text),
    escape(some_other_text),
))

You should instead use:

format_html("{} <b>{}</b> {}",
    mark_safe(some_html),
    some_text,
    some_other_text,
)

This has the advantage that you don’t need to apply 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 conditional_escape() which (ultimately) calls force_text() on the values.

doc_Django
2016-10-09 18:40:30
Comments
Leave a Comment

Please login to continue.