1

I have a flask app that returns a template with dynamically generated text. I want to bold specific words in the text variable based on a list variable that is also dynamically generated.

Lets say my two variables are as below

text = "Stephen went to the park on Tuesday with Sarah.
        Stephen couldn't go to my birthday party."

list=['Stephen', 'Sarah', 'Tuesday']

desired html output: Stephen went to the park on Tuesday with Sarah. Stephen couldn't go to my birthday party.

Im stumped with how to approach a problem like this, any help or direction will be much appreciated.

Edit: Python code

return render_template('results.html', ctext=boldened_text)

Html code

<h6>Your Text was</h6>
<div class="alert alert-info" role="alert"><p>{{ctext}}</p></div>
BadKarma1122
  • 87
  • 1
  • 9

2 Answers2

1
# Loop over all words
for word in list:
  # replace the word by bold tags with the word in between
  text = text.replace(word, '<b>%s</b>' % word)
Manuel
  • 534
  • 3
  • 9
1

For finer control, I'd advise using a for loop (simplified as a list comprehension in this example):

text = "Stephen went to the park on Tuesday with Sarah. Stephen couldn't go to my birthday party."

filter_list = ['Stephen', 'Sarah', 'Tuesday']

boldened = " ".join(["<b>{}</b>".format(word) if word.strip() in filter_list else word for word in text.split(" ")])

To see what this outputs use:

print(boldened)

Expected output:

"<b>Stephen</b> went to the park on <b>Tuesday</b> with Sarah. <b>Stephen</b> couldn't go to my birthday party."

NOTE: remember that in Python list is a type, don't use it as an identifier for variables.

Also, you're getting the <b> tags printed as plain text because you're not rendering your ctext variable as HTML, write this instead:

{{ ctext | safe }}

WARNING: only use safe with strings that you're absolutely sure are actually safe!

Good luck.

Malekai
  • 4,765
  • 5
  • 25
  • 60
  • It looks like your code is working for the most part, however my html page displays the tags alongside the text without formatting into bold ex: Stephen. Ill add my html side code to my original post. – BadKarma1122 May 12 '19 at 17:46
  • 1
    @BadKarma1122 I've updated my answer, accept if it works, let me know if it doesn't. – Malekai May 12 '19 at 18:02