Florian Ledermann
Florian Ledermann

Reputation: 3537

How to escape a newline character in a string literal in Django templates?

In my template, I want to check if a string stored in a variable contains a newline. However, I haven't found a way to escape the newline character in the string literal used in the check. The obvious

{% if "\n" in description %}
...
{% endif %}

does not work, seems to auto-escape the "\".

Of course I can always implement a simple custom filter or model method, but I thought there had to be an easier way. Searching for this on the web is hard as "escaping" in the context of Django templates is mostly concerned with escaping HTML, not string characters...

Upvotes: 1

Views: 2147

Answers (1)

jasonharper
jasonharper

Reputation: 9622

You could put a key in the context dict being passed to your template, call it newline perhaps, with a value of "\n". You could then do things like {% if newline in description %} in your template.

EDIT: I've checked the Django source, there really isn't a built-in way to do this. The only escape sequences that are processed in template string literals are backslash-quote and double-backslash.

Upvotes: 1

Related Questions