html.rst 1.4 KB

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