[Django] #33603: Backslashes in template tag arguments are escaped

26 views
Skip to first unread message

Django

unread,
Mar 27, 2022, 12:07:00 PM3/27/22
to django-...@googlegroups.com
#33603: Backslashes in template tag arguments are escaped
-------------------------------------------+------------------------
Reporter: bhch | Owner: nobody
Type: Bug | Status: new
Component: Template system | Version: 3.2
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------------+------------------------
I've written a custom template tag to replace parts of a value:

{{{
@register.simple_tag
def string_replace(value, old, new):
return value.replace(old, new)
}}}

And I'm using it to replace newline characters with commas in a user's
address:

{{{
{% string_replace user.address '\r\n' ',' %}
}}}

However, this doesn't work.

The reason is that when Django loads a template using Python's
`file.read()` function, the backslashes get escaped which means `\r\n`
becomes `\\r\\n`.

So, the `string_replace` tag actually receives `\\r\\n` instead of `\r\n`.
This also affects other tags as well.

Shouldn't Django pass the original string argument to the template tag as
intended?

--
Ticket URL: <https://code.djangoproject.com/ticket/33603>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
Mar 28, 2022, 6:52:09 AM3/28/22
to django-...@googlegroups.com
#33603: Backslashes in template tag arguments are escaped
-------------------------------------+-------------------------------------
Reporter: bhch | Owner: nobody
Type: | Status: closed
Cleanup/optimization |

Component: Template system | Version: 3.2
Severity: Normal | Resolution: wontfix

Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by Mariusz Felisiak):

* status: new => closed
* type: Bug => Cleanup/optimization
* resolution: => wontfix


Comment:

Thanks for the report, however I don't think Django can do much here, and
any change would be backward incompatible. Please also take into account
that it works when `value` is passed directly, e.g.
{{{
{% string_replace "My address\r\nwith newline characters" "\r\n" "," %}
}}}
I'd recommend to create a new filter, e.g. `{% replace_newline value %}`,
pass arguments via context variables, or escape/unescape arguments in
`string_replace()`.

--
Ticket URL: <https://code.djangoproject.com/ticket/33603#comment:1>

Reply all
Reply to author
Forward
0 new messages