38

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...

0

1 Answer 1

65

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

{% autoescape false %} {{ 'item1|item2|item3' | replace("|", "<br/>") }} {% endautoescape %} 
Sign up to request clarification or add additional context in comments.

7 Comments

but what if item1, item2, item3 needs to be escaped!?
Technically correct, but are you sure you want to disable autoescape? Do you want to let users inject their own HTML into your template?
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
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 %}<br />{{ line }}{% endfor %}
Suggest to have a look at this answer, which I think offers the optimal approach: stackoverflow.com/a/65424688/4400069
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.