#36519: The center template filter is inconsistent when adding an odd amount of
padding
-------------------------------+-------------------------------------------
Reporter: Lily Acorn | Type: Bug
Status: new | Component: Template system
Version: 5.2 | Severity: Normal
Keywords: center filter | Triage Stage: Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------+-------------------------------------------
Django supports a template filter for centering strings: `{{
"Django"|center:10 }}` which adds padding around the string to reach the
provided length. In this simple case, the template is rendered as
`··Django··` (where `·` represents a space character).
Things get weird when the total amount of padding required is an odd
number. For example, `{{ "odd"|center:6 }}` becomes `·odd··`, but `{{
"even"|center:7 }}` becomes `··even·`. Note that the side with the extra
space character is inconsistent.
The cause of this quirk is that Django’s `center` filter directly calls
Python’s `str.center` method,
[
https://github.com/python/cpython/issues/67812 which maintains this
behaviour for backwards compatibilty reasons].
Python also supports centering via f-strings (and `str.format`):
{{{
>>> f"{'odd':^6}"
'·odd··'
>>> f"{'even':^7}"
'·even··'
}}}
and this behaves consistently - always adding the extra unpaired space on
the right.
I think Django should match the f-string behaviour here.
--
Ticket URL: <
https://code.djangoproject.com/ticket/36519>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.