Flask: show flash messages in alertbox

mini.1601 picture mini.1601 · Nov 7, 2015 · Viewed 12.1k times · Source

I've been working on flask and I came across flash. It displays a message on page if flash was called on the server side. However, I'd like to display the contents get_flashed_messages() in an alertbox. I tried to make JS function and pass {{message}} but the loop prints the call i.e. takes the call as a string.

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

IS there any way to go about it?

Answer

r-m-n picture r-m-n · Nov 7, 2015

You can create JS variable containing messages

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <script>
      var messages = {{ messages | safe }};
      for (var i=0; i<messages.length; i++) {
        alert(messages[i]);
      }
    </script>
  {% endif %}
{% endwith %}