| 1 |
.. currentmodule:: markupsafe |
| 2 |
|
| 3 |
HTML Representations |
| 4 |
==================== |
| 5 |
|
| 6 |
In many frameworks, if a class implements an ``__html__`` method it |
| 7 |
will be used to get the object's representation in HTML. MarkupSafe's |
| 8 |
:func:`escape` function and :class:`Markup` class understand and |
| 9 |
implement this method. If an object has an ``__html__`` method it will |
| 10 |
be called rather than converting the object to a string, and the result |
| 11 |
will be assumed safe and not escaped. |
| 12 |
|
| 13 |
For example, an ``Image`` class might automatically generate an |
| 14 |
``<img>`` tag: |
| 15 |
|
| 16 |
.. code-block:: python |
| 17 |
|
| 18 |
class Image: |
| 19 |
def __init__(self, url): |
| 20 |
self.url = url |
| 21 |
|
| 22 |
def __html__(self): |
| 23 |
return f'<img src="{self.url}">' |
| 24 |
|
| 25 |
.. code-block:: pycon |
| 26 |
|
| 27 |
>>> img = Image("/static/logo.png") |
| 28 |
>>> Markup(img) |
| 29 |
Markup('<img src="/static/logo.png">') |
| 30 |
|
| 31 |
Since this bypasses escaping, you need to be careful about using |
| 32 |
user-provided data in the output. For example, a user's display name |
| 33 |
should still be escaped: |
| 34 |
|
| 35 |
.. code-block:: python |
| 36 |
|
| 37 |
class User: |
| 38 |
def __init__(self, id, name): |
| 39 |
self.id = id |
| 40 |
self.name = name |
| 41 |
|
| 42 |
def __html__(self): |
| 43 |
return f'<a href="/user/{self.id}">{escape(self.name)}</a>' |
| 44 |
|
| 45 |
.. code-block:: pycon |
| 46 |
|
| 47 |
>>> user = User(3, "<script>") |
| 48 |
>>> escape(user) |
| 49 |
Markup('<a href="/users/3"><script></a>') |