Home > Software engineering >  Replacing a double space with a break tag in flask
Replacing a double space with a break tag in flask

Time:12-13

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 %}

CodePudding user response:

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.

  • Related