30

I have some data in jinja2 like this

'item1|item2|item3'

And I want to turn it into rendered linebreaks. However, when I replace it with br/ tags, I get the br tags rendered on the page. So

{{ 'item1|item2|item3' | replace("|", "<br/>") }}

renders as

item1<br/>item2<br/>item3<br/>

When I want

item1
item2
item3

on my page. I feel like I'm missing some obvious trick here...

mcpeterson
  • 4,894
  • 4
  • 24
  • 24

1 Answers1

57

This has to do with autoescaping. Solution that worked for me was:

{% autoescape false %}
  {{ 'item1|item2|item3' | replace("|", "<br/>") }}
{% endautoescape %}
mcpeterson
  • 4,894
  • 4
  • 24
  • 24
  • 10
    but what if item1, item2, item3 needs to be escaped!? – Khaled Nov 15 '17 at 03:26
  • this also works for `replace(variable, 'anyvalue')` thanks ! – Beqa Bukhradze Jul 21 '18 at 20:07
  • 2
    Technically correct, but are you sure you want to disable autoescape? Do you want to let users inject their own HTML into your template? – Right leg Jan 21 '19 at 12:46
  • 2
    I updated the snippet with explicit `escape` for the original input but the official jinja2 doc [mentions how to achieve the same result with a custom filter](http://jinja.pocoo.org/docs/2.10/api/#custom-filters) – Nikolay Shebanov Mar 15 '19 at 19:38
  • 3
    I didn't want to turn off autoescape so instead I did this in Python ```new_variable = mystring.split('\n')``` and then, passing it to my Jinja template, I used a for loop: ```{% for line in new_variable %}
    {{ line }}{% endfor %}```
    – DangerPaws Mar 14 '20 at 10:49
  • 1
    Suggest to have a look at this answer, which I think offers the optimal approach: https://stackoverflow.com/a/65424688/4400069 – Tom M Dec 23 '20 at 12:56