Search code examples
pythonhtmldjangodjango-templatesjinja2

How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?


I'm currently trying to escape a variable using django templating filters as below. I use a jinja2 template engine instead of just django's primary templateing engine

{{ my_variable|escape|linebreaks }}

the output of a string with newlines is as follows:

Lorem ipsum <br /> dolor sit amet <br />rg srg
gs rgsr rsg serg<br />r srg

Ideally the

<br />

is not supposed to be escaped, as it is added by the "linebreaks" filter. There are no html tags with the original string.

I've tried:

{{ my_variable|linebreaks|escape }}

But, it turns out even worse:

<p>Lorem ipsum <br /> dolor sit amet <br />rg srg</p>
<p>gs rgsr rsg serg<br />r srg</p>

Does anyone knows whether I did something wrong with applying the template filter, and/or able to point me in the right direction?

Thanks.


Solution

  • Silly me, it seems that I can use:

    {{ my_variable|forceescape|linebreaks }}
    

    to force the 'escape' filter to apply first. By default 'escape' only apply at end of all other filters despite of position, so force_escape is the other most simple alternative.