How to flashing a message with link using Flask flash? How to flashing a message with link using Flask flash? flask flask

How to flashing a message with link using Flask flash?


The other answers here focus on changing your template to allow all flash messages to be marked as safe, which may not be what you want.

If you just want to mark certain flashed messages as safe, wrap the text passed to flash() in Markup(). (Flask API Docs for Markup)

For example, instead of:

flash('Successfully registered, please click <a href="/me" class="alert-link">here</a>')

Wrap the string in Markup() like this:

flash(Markup('Successfully registered, please click <a href="/me" class="alert-link">here</a>'))

As always, you will need to import Markup from the flask package something like:

from flask import Markup


You need to render a template after calling flash() which should then get the message using get_flashed_messages(). You need to adjust your code to call a template after calling flash(). flash sends the message to next request which can be extracted by the template. The template can look something like:

{% with messages = get_flashed_messages() %}    {% if messages %}    <ul class=flashes>    {% for message in messages %}        <li>{{ message | safe }}</li>    {% endfor %}    </ul>  {% endif %}{% endwith %}

In your view code, I would add a render_template right after the flash() call. Something like:

flash('success')return render_template('whatever.html')   


Escaping HTML is the default behavior, so pass it through the safe filter to display the HTML unescaped:

{{ message|safe }}