Replacing a double space with a break tag in flask

Question:

I have a database with each row being a particular event. Every event has an associated information column. In flask I’m trying to replace double spaces in the information string with a <br> tag for the html document. However when I do it the naive way with .replace(' ','<br>') it of course only puts this into the actual text. What would be a good way of going about this issue?

Currently the relevant part of my python code looks like this:

kalender = Kalender.query.order_by(Kalender.datum).all()
for k in kalender:
    if k.datum < datetime.date.today():
        db.session.delete(k)
        db.session.commit()

and the relevant part of the html document is only:

{% for arr in kalender %}
<p>{{arr.info}}</p>
{% endfor %}
Asked By: Aron Fredriksson

||

Answers:

You can split the string in the template and add a <br> tag after each part:

import jinja2

s = 'Hello world  Hello world  Hello world'

template = jinja2.Template(
"""
{% for part in s.split('  ') %}
    {{ part }}<br>
{% endfor %}
"""
)
print(template.render(s=s))

Output:

    Hello world<br>

    Hello world<br>

    Hello world<br>

In your case, of course s corresponds to the info attribute of each Kalendar instance.

Answered By: snakecharmerb
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.