0

I have a function in flask which is supposed to highlights text if some keywords are present in it.

For e.g. if text is "This is amazing" and keywords are ["is", "amazing"]

The output I get is:

"This <mark>is</mark> <mark>amazing</mark>"

I am storing the above output in a variable and passing it into render_template function in flask.

code for the function below:

    if request.method == "POST":
        text = request.form["text"]
        keywords_text = request.form["keywords"]
        keywords = list(keywords_text.split(" "))
  
        replacement = lambda match: re.sub(r'([^\s]+)', r'<mark>\1</mark>', match.group())
        processed_text = re.sub("|".join(map(re.escape, keywords)), replacement, text, flags=re.I)

        return render_template('index.html', processed_text=processed_text)

The problem I am facing now is when I am passing the processed_text variable in my template the I am getting it as HTML encoded text itself and not the highlighted keywords.

code for template below:

<div>
        <form action="/transform" method="post">
        <textarea name="text" cols="50" rows="10" style="margin:10px;">{{processed_text}}</textarea>
</div>

Can someone help me how should I get the desired result?

Thanks a lot in advance.

Saitama
  • 13
  • 3
  • Does this answer your question? [Passing HTML to template using Flask/Jinja2](https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2) – Patrick Yoder Jun 23 '22 at 16:34
  • 1
    No I have checked that answer and tried with safe keyword. That's not working for me. – Saitama Jun 27 '22 at 11:18

0 Answers0