How to apply django / jinja2 "escape" and "linebreaks" filter templates?

I am currently trying to avoid a variable using django template filters, as shown below. I use the jinja2 template engine instead of the simple django primary template engine.

{{ my_variable|escape|linebreaks }} 

the output of a line with newline characters is as follows:

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

Perfectly

 <br /> 

it is not intended to be reset, as it is added by the linebreaks filter. There are no html tags with source string.

I tried:

 {{ my_variable|linebreaks|escape }} 

But it turns out to be even worse:

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

Does anyone know if I did something wrong using the template filter and / or could point me in the right direction?

Thanks.

+4
source share
2 answers

Stupid to me, it seems I can use:

 {{ my_variable|forceescape|linebreaks }} 

to force the "escape" filter. By default, "escape" is applied only at the end of all other filters, regardless of position, so force_escape is another simplest alternative.

+2
source

So, do you use the django linebreaks filter in the jinja2 template? In this case, I would suggest that the way django places the security string may not be compatible with jinja2, therefore avoiding the tags added by django (if autoescape is active).

What if you added a safe filter from jinja2 to the end?

 {{ my_variable|escape|linebreaks|safe }} 

Otherwise, there is an example for a custom filter in the jinja2 documentation, which seems to be similar to django line breaks. http://jinja.pocoo.org/docs/api/#custom-filters

 import re from jinja2 import evalcontextfilter, Markup, escape _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') @evalcontextfilter def nl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result 
+4
source

Source: https://habr.com/ru/post/1338468/


All Articles