Proposal: Support the __html__ method as an alternative/addition to the
__str__ for turning objects into strings in the template layer.
If this has been discussed before, please point me to it; I couldn't find
anything with the search function.
Some custom classes may have, in addition to a __str__ representation, a
natural representation that is better suited for HTML output. Example:
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __str__(self):
return '%s %s' % (self.currency, self.amount)
def __html__(self):
# Always show amount and currency on same line
return '%s\xa0%s' % (self.currency, self.amount)
`conditional_escape` and friends already consider the __html__ method, and
this works out well:
>>> str(Money(1, '$'))
'$ 1'
>>> conditional_escape(Money(1, '$'))
'$\xa01'
In templates however it doesn't work that way because variables are always
turned into strings before stuffing them into `conditional_escape`
(see
https://github.com/django/django/blob/98706bb35e7de0e445cc336f669919047bf46b75/django/template/base.py#L977).
My suggestion is to change the behaviour of that function so that it works
as follows:
- Given I write {{ foo }}
- Does foo have a __html__ method? If yes, return `foo.__html__()`
- Otherwise, return `conditional_escape(str(foo))`
Do think that's a good idea?
Jonas
--
You received this message because you are subscribed to the Google Groups
"Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-developers/ea088de2-e538-4808-a7fd-8726929e2b91%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.